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?
Things that come to mind (without seeing your code).
EOF
could be defined differently than you expectsourcefile.peek()
doesn't advance the file pointer. Are you advancing it manually somehow, or are you perhaps constantly looking at the same character?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 asEOF
, unless by chanceEOF
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.Consulting the Standard,
As for
sgetc()
,And
underflow
,So yep, returns
EOF
on end of file.An easier way to tell is that it returns
int_type
. Since the values ofint_type
are just those ofchar_type
plus EOF, it would probably returnchar_type
if EOF weren't possible.As others mentioned,
peek
doesn't advance the file position. It's generally easiest and best to just loop onwhile ( input_stream )
and let failure to obtain additional input kill the parsing process.