1 2 3
|
while (!fin.eof())
{
fin >> temp;
|
don't loop on eof, loop on the reading operation
while( fin>>temp ){
that way you won't have the "last value counted twice" issue.
Suppose that your file ends with a line break
42\n
after consuming the last number you'll have
\n, so you didn't reach the end-of-file. You attempt to read one more time and fail.
Notice where you check for
eof(), that last attemp (that failed) will be counted as valid.
Now suppose that the file doesn't end with a line break
42, then after consuming the last number you do reach the end-of-file, and will have the correct count.
¿how could you decide whether you need to do --n or not?
you wouldn't have this issue if you check the reading operation.