I'm trying to load in input from a file, representing students. Each student has a name and list of scores, like so:
Name John Wayne
Scores 100 90 80 100 0
Name Bob Dwight
Scores 0 0 10 100
Name Dummy Student
Scores 0 0
I am reading this through a class structure like so. A classroom object keeps a list of all students.
class Student
{
string first_name;
string last_name;
vector<int> quizzes;
public:
void read(istream & in){
string line;
// Name initialization
getline(in, line);
stringstream namereader(line);
string word;
namereader >> word; // Go past "Name"
namereader >> word;
first_name = word; // Second word in a line is firstname
namereader >> word;
last_name = word; // Third word in a line is lastname
// Quizzes
getline(in, line); // line after name contains quiz scores
stringstream quizreader(line);
quizreader >> word; // Go past "Quiz"
int quizgrade;
while(quizreader >> quizgrade){ // Read quiz scores and insert
quizzes.insert(quizzes.end(), quizgrade);
}
// Putting quizreader.str(""), quizreader.clear() does not work
//Empty Line between each student
getline(in, line);
}
void print(ostream & out) const{
out << "Name " << first_name << " " << last_name << endl;
out << "QZ Ave: " << endl;
for (int i : quizzes){
cout << i << " ";
}
cout << endl;
}
friend ostream & operator <<(ostream &out, const Student & student){
student.print(out);
return out;
}
friend istream & operator >>(istream &in, Student & student){
student.read(in);
return in;
}
};
Classroom:
class Classroom{
vector<Student> students;
public:
void print(ostream & out) const{
for (Student s : students){
out << s << endl;
}
}
void read(istream & in){
Student s;
while (in >> s){
students.insert(students.end(), s);
}
}
friend ostream & operator <<(ostream &out, const Classroom & cl){
cl.print(out);
return out;
}
friend istream & operator >>(istream &in, Classroom & cl){
cl.read(in);
return in;
}
};
Main function:
int main(){
ifstream in("classroom.txt");
Classroom cl;
in >> cl;
cout << cl;
return 0;
}
When I try to print this out, I noticed that my stringstream does not reset across the calls done by the for loop in Classroom::read.
This means the output of the main function is:
John Wayne
Scores 100 90 80 100 0
Bob Dwight
Scores 100 90 80 100 0 0 0 10 100
Dummy Student
Scores 100 90 80 100 0 0 0 10 100 0 0
I have tried clear all of my stringstreams with .clear(), and .str(""). They don't work, regardless of where I place them in read(), and in which order. What is curious to me is that quizreader
retains all of the previous numbers, but namereader
keeps going on and takes the next name as expected. Is this a problem with opening multiple stringstreams? Improper initialization?
I am assuming all inputs are of the correct type, those problems I will be fixing later. I have read almost every post I could find on this site related to this topic, but I cannot seem to find a working solution.