Detecting EOF in C++ from a file redirected to STDIN

╄→尐↘猪︶ㄣ 提交于 2019-11-29 08:39:29

@Jacob had the correct solution but deleted his answer for some reason. Here's what's going on in your loop:

  1. cin is checked for any of the failure bits (BADBIT, FAILBIT)
  2. cin reports no problem because nothing has yet been read from the file.
  3. getline is called which detects end of file, setting the EOF bit and FAILBIT.
  4. Loop executes again from 1, except this time it exits.

You need to do something like this instead:

std::string input;
while(std::getline(std::cin, input))
{
     //Have your way with the input.
}

How about this:

string input;
while(getline(cin, input)) {
  //do something with input...
}

EDIT: please note, in the example below, I show you "how to detect EOF". As @Billy has pointed out, you probably want to use good() instead of eof() to detect any error condition or eof. I had included information about this at the end of my answer, but it's important, so I'm adding this note at the top to ensure that it's clear.

(original answer follows)


You want this:

string input;
while( !cin.eof() ) {
   getline(cin, input);
}

using operator! on an iostream only checks whether a failure or other error condition has occurred. ios::operator!().

You can use good() in place of !eof() to check for any of the conditions eof, badbit, or failbit. ios::good().

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!