issue with looping a ifstream

Jun 28, 2013 at 11:22pm
Using any numbers found in a text file for example 3,5, and 8. It appears the the last number such as 8 will be added twice in the total number and I am not quite sure as to why.... or how to resolve the issue.
So in this example the total will be 24 instead of 16.

1
2
3
4
5
6
7
8
9
10
11
12
13
textfile.open ("input.txt", ios::in);
if (textfile.is_open()){
while (!textfile.eof()) {
  textfile >> number; 
  total = total + number; 
} 
textfile.close(); 
}
cout << total << endl;

return 0;
}
Jun 28, 2013 at 11:30pm
Don't loop on eof(), because that only becomes true once you have tried and failed to read past the end of the file, causing an extra run of the loop to occur. Instead, loop on the value textfile >> number.
Jun 28, 2013 at 11:53pm
ahhh that makes sense, Thank you.
Topic archived. No new replies allowed.