Ok let me try to explain in more detail.
The original code:
1 2 3 4 5 6 7 8
|
while (!fin.eof())
{
fin.get(ch);
if (ch!='\n')
{
count++;
}
}
|
Assume everything is going along smoothly, characters are being read one at a time from the file.
Then we get to line 3 to read the very last character.
fin.get(ch);
that was ok,
ch
now contains the last character in the file. No flags were set. The count is incremented (assume it was not a '\n').
Control goes back to the start of the loop, line 1. the eof flag is not yet set. So the loop is executed again. This time the fin.get() cannot read a character. The end of file has been reached.
eof
is set.
fail
is set.
But there is no check here.
Execution continues to the next line and count is incremented
again - because
ch
remains unchanged from the previous time.
So the reason for the incorrect result is the logic error. After doing fin.get() there was no test on whether or not it succeeded and by the time the eof flag is set the loop has already executed one time too many.