Return value of ifstream.peek() when it reaches the end of the file

superlazyname picture superlazyname · Sep 14, 2010 · Viewed 11.5k times · Source

I was looking at this article on Cplusplus.com, http://www.cplusplus.com/reference/iostream/istream/peek/

I'm still not sure what peek() returns if it reaches the end of the file.

In my code, a part of the program is supposed to run as long as this statement is true

(sourcefile.peek() != EOF)

where sourcefile is my ifstream.

However, it never stops looping, even though it has reached the end of the file.

Does EOF not mean "End of File"? Or was I using it wrong?

Answer

Mark Ransom picture Mark Ransom · Sep 14, 2010

EOF is for the older C-style functions. You should use istream::traits_type::eof().

Edit: viewing the comments convinces me that istream::traits_type::eof() is guaranteed to return the same value as EOF, unless by chance EOF has been redefined in the context of your source block. While the advice is still OK, this is not the answer to the question as posted.