How to know if the next character is EOF in C++

2020-02-04 20:15发布

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.

标签: c++ eof
7条回答
Fickle 薄情
2楼-- · 2020-02-04 20:38

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 be true.

So, instead of if (file.peek() == file.eof()) you should have if (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).

查看更多
乱世女痞
3楼-- · 2020-02-04 20:40

This should work:

if (file.peek(), file.eof())

But why not just check for errors after making an attempt to read useful data?

查看更多
够拽才男人
4楼-- · 2020-02-04 20:47

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.

查看更多
仙女界的扛把子
5楼-- · 2020-02-04 20:47

Usually to check end of file I used:

    if(cin.fail())
    {
        // Do whatever here
    }

Another such way to implement that would be..

    while(!cin.fail())
    {
        // Do whatever here
    }

Additional information would be helpful so we know what you want to do.

查看更多
Animai°情兽
6楼-- · 2020-02-04 20:58

istream::peek() returns the constant EOF (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:

int c = file.peek();
if (c == EOF) {
  if (file.eof())
    // end of file
  else
    // error
} else {
  // do something with 'c'
}

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.

查看更多
何必那么认真
7楼-- · 2020-02-04 20:59

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. :-)

查看更多
登录 后发表回答