File IO - eof problem

Hi, I'm having a difficult time using eof. After done some trial and error, I still getting the last input being read twice.

1
2
3
4
5
6
7
8
9
 
while(sum.eof() == false)
 {
  sum >> number;
  sum1 = sum1 + number;
  cout << number << " ";
 } 
 sum.close();
 cout << "Sum : " << sum1 << endl;


Supposed that the numbers are 20, 30, 40 respectively, when i run the code, it gave the following output:

20 30 40 40 Sum : 130 


Anyone can help me with eof thing? A more explanation on how to use eof would be suffice :)

-cplusx2
1
2
3
4
5
6
7
8
9
10
11
12
while( sum.eof() == false )
{
    // let us say sum.eof() is false at this point (the last read was successful; 
    // we have not reached end-of-file just yet;

    sum >> number ;
    // but when we try to read one more number, end-of-file is reached and the read fails
    // sum.eof() == true at this point; but we have no way of knowing it; we are not checking for it

    sum1 = sum1 + number ;
    cout << number << " " ;
}


Check for failure (end-of-file) of input immediately after (instead of before) the attempted input


1
2
3
4
5
while( sum >> number ) // while we have successfully read in another number
{
    sum1 = sum1 + number ;
    cout << number << " " ;
}

Wow, thanks man, it works!!! Btw, if i put sum >> number; before the while(! eof()), the output would also be the same but your code is simple and shorter. Thanks again dude!
Topic archived. No new replies allowed.