How do I check for the end of the file?

If I am reading numbers from a file, how do I check to see if there are more numbers to input? or how do i set the program to stop reading after there are no more numbers to input? i am a beginner so nothing too complicated please
1
2
3
4
5
ifstream fin("file");
while (fin) {
   int num;
   fin >> num;
}
To add a bit of explanation to ropez reply, an instance of a file stream (fin in the above code) actualy returns a state value which will indicate any error conditions.
These will include failing to opend the file and also read / write errors.
so in the example above, the first time into the while loop you are actualy testing if the file opened correctly and on susequent itterations testing if the file read OK.
If you need to test for these seperately you can use the fail() and eof() methods
EG
1
2
3
4
5
6
7
8
9
10
11
12
13
int num;
ifstream fin("file");
if (fin.fail())
{
   cout <<  "Failed To Open" << endl;
}
else
{
   while (!fin.eof())
   {
      fin >> num;
   }
}


If you want more details, please try the reference section, in particular

http://www.cplusplus.com/reference/iostream/

which has lots more info.
Last edited on
Topic archived. No new replies allowed.