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条回答
仙女界的扛把子
2楼-- · 2020-02-04 21:03

You didn't show any code you are working with, so there is some guessing on my part. You don't usually need low level facilities (like peek()) when working with streams. What you probably interested in is istream_iterator. Here is an example,

  cout << "enter value";

  for(istream_iterator<double> it(cin), end; 
      it != end; ++it)
  {
     cout << "\nyou entered value " << *it;
     cout << "\nTry again ...";
  }

You can also use istreambuf_iterator to work on buffer directly:

  cout << "Please, enter your name: ";

  string name;
  for(istreambuf_iterator<char> it(cin.rdbuf()), end;
    it != end && *it != '\n'; ++it)
  {
    name += *it;
  }
  cout << "\nyour name is " << name;
查看更多
登录 后发表回答