Lambda <> wrote:
> My question is how does the program know I have read all the data
> from the 2 lines file. the istream& read_hw(istream& in,
> vector<double>& hw) function will do in.clear(); so even cin
> encounter EOF, the eofbit will be cleared.
Not quite...
> I think the main function will try to read the non exist third line
> and fail. But actually the program works! How does the code know it
> has read all the data??
Step through the program by hand, assume that the file is empty. What
will happen?
1: while (read(cin, record)) {
2: (inside read) is >> s.name >> s.midterm >> s.final;
At this point the eof is encounterd.
3: read_hw(is, s.homework);
4: (inside read_hw) if (in) {
'in' returns 'false' in this case so the entire block is passed up.
I.E., in.clear() isn't called.
5: return in;
6: (back inside read) return is;
7: back to (1) the while loop is exited.
Hope the above helps you understand the code, and gives you a tool to
understand other code in the future.
When I started programing (back in the stone ages.

I didn't have
access to a mainframe so I had to step through my code by hand to see if
it worked. I still use the method today.