I'm need to know if the next char in ifstream
is the end of file. I'm trying to do this with .peek()
:
if (file.peek() == -1)
and
if (file.peek() == file.eof())
But neither works. There's a way to do this?
Edit: What I'm trying to do is to add a letter to the end of each word in a file. In order to do so I ask if the next char is a punctuation mark, but in this way the last word is left without an extra letter. I'm working just with char
, not string
.
file.eof()
returns a flag value. It is set to TRUE if you can no longer read from file. EOF is not an actual character, it's a marker for the OS. So when you're there -file.eof()
should betrue
.So, instead of
if (file.peek() == file.eof())
you should haveif (true == file.eof())
after a read (or peek) to check if you reached the end of file (which is what you're trying to do, if I understand correctly).This should work:
But why not just check for errors after making an attempt to read useful data?
There is no way of telling if the next character is the end of the file, and trying to do so is one of the commonest errors that new C and C++ programmers make, because there is no end-of-file character in most operating systems. What you can tell is that reading past the current position in a stream will read past the end of file, but this is in general pretty useless information. You should instead test all read operations for success or failure, and act on that status.
Usually to check end of file I used:
Another such way to implement that would be..
Additional information would be helpful so we know what you want to do.
istream::peek()
returns the constantEOF
(which is not guaranteed to be equal to -1) when it detects end-of-file or error. To check robustly for end-of-file, do this:You should know that the underlying OS primitive,
read(2)
, only signals EOF when you try to read past the end of the file. Therefore,file.eof()
will not be true when you have merely read up to the last character in the file. In other words,file.eof()
being false does not mean the next read operation will succeed.For a stream connected to the keyboard the eof condition is that I intend to type Ctrl+D/Ctrl+Z during the next input.
peek()
is totally unable to see that. :-)