feof in standard c++ library

Started by
6 comments, last by MaulingMonkey 18 years, 2 months ago
Hello! I'm switching from the old c library (printf) to the new c++ one (cout) and I need to know if there's a function similar to feof() to be able to do:

while(! end_of_file(my_file) )
{
  go_on_and_read_for_everlasting_peace(my_file);
}
What is this function? or if it doesn't exist, what's the workaround?
Advertisement
if you use file streams, the good() method:


std::ifstream in("in.txt");
while( in.good() )
{
// do stuff
}

there is also a eof() method
#include <fstream>#include <string>std::ifstream file( "filename" ); //std::ifstream is-a std::istreamwhile ( file.good() ) //includes "!file.eof()"{    std::string line, word;    char character;    std::getline( file , line );    file >> word;    file >> character;}
ok thanks!

I had had a look at that eof() method but it only accepted a int argument. Anyways I'll use good() now, thanks!
If you are using the iostream libraries, and not the stdio.h (and you realy should in C++)
you can use the ifstream::eof() function.

ifstream fin;
...
while(!fin.eof())
{
...
}

or

while(fin.good())
{
...
}


Im not sure if they do the exact same thing though...

EDIT:
Whow, I must be typing slow...
Quote:Original post by Trillian
I had had a look at that eof() method but it only accepted a int argument.


Look at better docs then:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vcstdlib/html/vclrfbasicioseof.asp
file.good() doesn't just refer to end of file. file.eof() does.

file.good() can become false on EOF, on a failed input operation (e.g. you try to read a number and there are only letters there) or if the stream itself goes "bad".

file.good() == !( file.eof() | file.fail() | file.bad() );
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Quote:Original post by pulpfist
Im not sure if they (!eof and good) do the exact same thing though...


They don't.

file.good() is synonymous with !( file.eof() || file.bad() || file.fail() )

EDIT: Beaten by Fruny D:

This topic is closed to new replies.

Advertisement