Regarding Eof function

Oct 22, 2008 at 4:19am
I would be glad if someone can help me out...

In our class teacher told us to check for eof using 'if condition only' and not to use 'while'..Its all totally confusing.

How do you use the eof function..is there a particular method?

Oct 22, 2008 at 4:31am
It's basically <name>.eof().

Ex:

1
2
3
4
5
6
7
if(!file.eof()) { //if file is not at the end
   //do stuff
   //FYI: this won't check for an error, like if the stream is corrupted you won't get .eof()
   //you should check for file.good() if you want to check if the stream is good
} else {
   //file is ended
}
Oct 22, 2008 at 11:18am
I use eof() in this way:
1
2
3
4
5
6
7
char mychar;
while(true)
{
    file.get(mychar);
    if (flie.eof()) break;
    //...
}

As a condition for the if so that I can test if the stream has reached the end each time I get a value from there.
If you write like this:
1
2
3
4
5
6
char mychar;
while(!flie.eof())
{
    file.get(mychar);
    //...
}
the end of stream will be checked after the loop so you can get wrong values.


But I do this only when I have to manage a loop checking for all the characters in the stream
Last edited on Oct 22, 2008 at 11:20am
Oct 23, 2008 at 10:12am
Thanks...I understand it now. Our textbook is very confusing....Now its ok..

Thanks again.
Topic archived. No new replies allowed.