-2

I'm running a while loop to read from an input file and write to an output file. The program appears to work perfectly except the final line is read twice. I believe this code is supposed to loop until the file has nothing left to be read and closes.

while (my_input_file) {
my_output_file << getStudentID() << "  " << studentScores() << " ";
totalScore();
calculatePercentage();
calculateGrade();
}
  • 2
    I don't see where you are reading, but I believe you've stumbled over a variant of [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – user4581301 Oct 21 '19 at 23:34
  • 1
    Unfortunately there's not enough here to see exactly what's wrong. We need more context. Could you [edit your question](https://stackoverflow.com/posts/58495355/edit) and post a [minimal example](http://stackoverflow.com/help/mcve)? –  Oct 21 '19 at 23:36

1 Answers1

0

The istream doesn't know it has reached the end of the file until after it tried to read past the end of the file. If you have only read exactly the contents of the file, the istream still thinks that it's good to go, which means you need to insert istream::fail checks after trying to read something from the file.