As with most problems, you can solve this one by breaking it down into smaller ones.
To read the student info, start with a function that reads a line with colon-separated fields. I'll call these the keyword and the value. So you want something like:
1 2
|
// Read a line with format "key : value". Return true on success.
bool readKeyAndVal(string &key, string &val, istream &is);
| |
Write this function, test it with a short main() program.
Next you need methods that will read and write the info for a student This will call readKeyAndVal().
1 2 3 4 5
|
struct Student {
...
bool read(istream &is); // read the student info from is
bool write(ostream &os); // write the student info to os
};
| |
It would be better to create << and >> operator.s If you don't know those are, then don't worry, just create the read() and write() methods. Again, test these out. Read student info and print it out.
Finally you need to read the lecture info and count the number of lectures. Read the title line for the lecture, then skip whitespace. Now you can use peek() to look at the first character of the next line. If it's a '-' then it's a lecture for the current course. Otherwise it's the start of a new lecture:
1 2 3 4 5
|
struct Course{
...
bool read(istream &is);
bool write(ostream &os);
};
| |
With these building blocks, the code practically writes itself:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
int main(){
Student professor;
ifstream inputFile;
inputFile.open("psuid.txt");
while(!inputFile){
cout << "File not opened!" << endl;
}
professor.read(inputFile);
Course dummy;
while (dummy.read(inputFile)) {
professor.courses.push_back(dummy);
}
// Print prof info
cout << professor;
// print course info for each course
for (int i=0; i<processor.courses.size(); ++i) {
cout << professor.courses[i] << '\n';
}
}
| |