fstream

I have some newbie question.When I trying to read data from file the last block is reading two times .The condition in loop is (!eof) What am I doing wrong???
This is my code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <fstream>
#include <iostream>
using namespace std;
int main( int argc, char* argv[] ) {
   ifstream in( "some_file" );
   
   int count = 0, num;


   while( !in.eof() ) {
    in >> num;
    count ++ ;


   }
   
    cout << count ;



}






The content of "some_file" is
1
2
3
4
1
2
3
4


And the output is
5


-holtaf
Don't check eof to see if there is anything else to read. At times input functions will not find it. For example, if there is a space after the last digit. You should instead check the fail flag after the input. That is,
1
2
while( in >> num )
   count++;
You could also use the .fail() method.
Thanks!
Topic archived. No new replies allowed.