C++ Help with reading text file. I need help with part of this project. I need t
ID: 671611 • Letter: C
Question
C++ Help with reading text file. I need help with part of this project. I need to read a text file that contains two sets of strings per line and store it into a dynamic array. I do not have much knowledge of dynamic arrays, and I cannot even get the program to read the lines correctly using normal arrays. Vectors are not allowed here.
Student File format
fname lname stuid
Course File format
stuid cname
An example with 2 student records would be:
Student File
Mary Smith 900678
John Jacobs 900134
Course File
900678 CIST2255
900678 MATH2345
900134 ENGL1105
900134 CIST3456
900678 CIST1234
My code: Scheduler.cpp
#include
#include
#include
#include
#include
#include "Scheduler.h"
#include
using namespace std;
void Scheduler::read()
{
const int SIZE1 = 4;
const int SIZE2 = 2;
string line[SIZE1][SIZE2];
size_t i = 0;
ifstream myfile("C:\Users\Nathan\Documents\Visual Studio 2013\Projects\Midterm Project\Midterm Project\love.txt");
string tmp; // temporary string to store the line-as-string
getline(myfile, tmp);
stringstream ss(tmp); // convert the line to an input stream to be able to extract
// the words
size_t j = 0; // the current word index
while (ss) {
ss >> line[i][j]; // here i is as above: the current line index
++j;
size_t numLines = 4;
for (i = 0; i < numLines; ++i) {
cout << i << ". ";
for (size_t j = 0; j < SIZE2; ++j) {
if (!line[i][j].empty()) {
getline(myfile, tmp);
stringstream ss(tmp);
//cout << line[i][j] << " ";
copy(istream_iterator(ss),
istream_iterator(),
ostream_iterator(cout, " "));
}
}
}
}
system("pause");
}
Scheduler.h
#include
#include
#include
#include
using namespace std;
class Scheduler{
private:
int degreetype = 0;
public:
void read(); //reads data from a file
void write(ofstream &out1); //output data to an output stream(ostream)
bool exists(); //return true or false depending whether or not a given word exists
void stdExists(); //^^ use either std::count() or std::find() inside here
};
Explanation / Answer
#include <vector>
#include <fstream>
#include <iostream>
#include <string>
class StringList
{
public:
StringList(): str(1000000), numberOfStrings(0)
{
std::ifstream myfile ("Read.txt");
if (myfile.is_open())
{
for (int i = 0; i < str.size(); i++)
{
getline(myfile, str[i]);
numberOfStrings++;
}
myfile.close();
}
}
StringList::~StringList()
{
std::ofstream os("Read.txt");
for (int i = 0; i <numberOfStrings; i++)
{
os << str[i] << std::endl;
}
}
private:
std::vector<std::string> str;
int numberOfStrings;
};
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.