I am trying to read an object from a file. It's a student who has a name, number of grades and grades. The problem is when I use istream_iterator method my function for reading only works for the first student.
1 2 3 4 5 6 7 8 9 10
istream& operator >> (istream& str, Student& s) // this is a friend function of class Student
{
str >> s.name;
int br;
str >> br;
copy(istream_iterator<int>(str), istream_iterator<int>(), back_inserter(s.vec)); // vector
return str;
}
Here is the code from main():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Student *arr[3]
for (int i = 0; i < 3; i++)
arr[i] = new Student();
myFile.open(fileName, ios::in);
for (int i = 0; i < 3; i++)
{
myFile >> *arr[i];
arr[i]->print(); // successfully prints the first student
// but the rest have default class constructor values
gr.push_back(*arr[i]); // pushing each student into a list
}
myFile.close();
if I replace the istream function with this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
istream& operator >> (istream& str, Student& s)
{
str >> s.name;
int br, n;
str >> br;
for (int i = 0; i < br; i++)
{
str >> n;
s.vec.push_back(n); // vector
}
return str;
}
it works perfectly. But I wanted to do the same using the istream_iterator method.
Line 7 in the first code snippet will read integers until it fails to do so. This will set the fail flag to true (str.fail() will return true). If you later try to read input from the stream while the fail flag is set it will automatically fail right away. What you need to do is to clear the flags.