C++ cin.eof() 功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4939251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:57:58  来源:igfitidea点击:

cin.eof() functionality

c++visual-c++iostream

提问by Mahesh

I understand that cin.eof()tests the stream format. And while giving input, end of characteris not reached when there is wrong in the input. I tested this on my MSV C++ 2010and am not understanding the strange results. No matter what I give the input, I am getting Format Errormessage that is present in the program.

我知道cin.eof()测试流格式。并且在给出输入时,如果输入错误,则不会到达字符结尾。我在MSV C++ 2010上对此进行了测试,但不明白奇怪的结果。无论我输入什么,我都会收到程序中存在的格式错误消息。

#include <iostream>
using namespace std;

int main()
{
    int i;
    cin>> i;

    if(!cin.eof())
    {
        cout<< "\n Format Error \n";
    }
    else
    {
        cout<< "\n Correct Input \n";
    }

    getchar();
    return 0;
}

Results I expected:

我预期的结果:

Values for i =

i = 的值

  1. 10 => Correct Inputbut the output is Format Error
  2. 12a => Format Error
  1. 10 =>正确输入但输出格式错误
  2. 12a =>格式错误

Could someone explain where I am going wrong. Thanks.

有人可以解释我哪里出错了。谢谢。

回答by sbi

std::cin.eof()tests for end-of-file(hence eof), not for errors. For error checking use !std::cin.good(), the built-in conversion operator (if(std::cin)) or the boolean negation operator (if(!std::cin)).

std::cin.eof()测试文件结尾(因此 eof),而不是错误。对于错误检查,使用!std::cin.good()内置转换运算符 ( if(std::cin)) 或布尔否定运算符 ( if(!std::cin))。

回答by Shivendra

Use a direct test of the status of the stream with:

使用流状态的直接测试:

while (cin >> i)
{
    ...
}

回答by AnT

For an input stream to enter the EOF state you have to actually make an attempt to read past the end of stream. I.e. it is not enough to reach the end-of-stream location in the stream, it is necessary to actually try to reada character past the end. This attempt will result in EOF state being activated, which in turn will make cin.eof()return true.

要使输入流进入 EOF 状态,您必须实际尝试读取流的末尾。即到达流中的流尾位置是不够的,有必要实际尝试读取超过尾端的字符。这种尝试将导致 EOF 状态被激活,这反过来会使cin.eof()return true。

However, in your case you are not only not doing that, you (most likely) are not even reaching the end of stream. If you input your 10from the keyboard, you probably finished the input by pressing the [Enter] key. This resulted in a new-line character being added to the input stream. So, what you are actually parsing with >>operator in this case is actually a 10\nsequence. Since you requested an intvalue from the stream, it only reads the numerical characters from the stream, i.e. it reads 1and 0, but it stops at \n. That \nremains in the stream. You never read it. So, obviously, your code never reaches the end-of-file position in the stream. You have to reason to expect cin.eof()to become truein such case.

但是,在您的情况下,您不仅没有这样做,而且(很可能)您甚至还没有到达流的末尾。如果您10从键盘输入您的,您可能通过按 [Enter] 键完成了输入。这导致一个换行符被添加到输入流中。因此,>>在这种情况下,您实际使用运算符解析的实际上是一个10\n序列。由于您int从流中请求了一个值,它只从流中读取数字字符,即它读取10,但它在 处停止\n。那\n仍然在流中。你从来没有读过它。因此,很明显,您的代码永远不会到达流中的文件末尾位置。在这种情况下,您必须有理由期望cin.eof()成为true

回答by Fred Nurk

#include <iostream>

int main() {
  using namespace std;
  int i;
  if (cin >> i) {
    cout << "Extracted an int, but it is unknown if more input exists.\n";
    char c;
    if (cin.get(c)) {  // Or: cin >> c, depending on how you want to handle whitespace.
      cin.putback(c);
      cout << "More input exists.\n";
      if (c == '\n') {  // Doesn't work if you use cin >> c above.
        cout << "But this was at the end of this line.\n";
      }
    }
    else {
      cout << "No more input exists.\n";
    }
  }
  else {
    cout << "Format error.\n";
  }
  return 0;
}

Also see Testing stream.good() or !stream.eof() reads last line twice.

另请参阅测试 stream.good() 或 !stream.eof() 读取最后一行两次

Sample session with the above program, note that input lines are marked with comments not present in the actual output:

上述程序的示例会话,请注意输入行标有实际输出中不存在的注释:

$ your-program
12  # input
Extracted an int, but it is unknown if more input exists.
More input exists.
But this was at the end of this line.

$ your-program
12a  # input
Extracted an int, but it is unknown if more input exists.
More input exists.

$ echo -n 12 | your-program
Extracted an int, but it is unknown if more input exists.
No more input exists.

$ your-program
a  # input
Format error.

回答by wilx

Assuming your input is line based, I suggest that you read the whole line using std::getline(). Once you have the line, you can analyse it and decide whether it contains correct or wrong input. Put the line into std::istringstreamand do something like the following:

假设您的输入是基于行的,我建议您使用std::getline(). 一旦你有了这条线,你就可以分析它并决定它是否包含正确或错误的输入。将行放入std::istringstream并执行以下操作:

Edit:Changed !! issto static_cast<bool>(iss)for compatibility with C++0x.

编辑:改变!! issstatic_cast<bool>(iss)与的C ++ 0x兼容性。

std::istringstream iss (line);
char ch;
long lval;
// read the input
iss >> lval;
// result variable will contain true if the input was correct and false otherwise
result
    // check that we have read a number of at least one digit length
    = static_cast<bool>(iss)
    // check that we cannot read anything beyond the value read above
    && ! (iss >> ch);

回答by UncleBens

cin.eof()test if the stream has reached end of file which happens if you type something like Ctrl+C (on Windows), or if input has been redirected to a file etc.

cin.eof()测试流是否已到达文件末尾,如果您键入 Ctrl+C(在 Windows 上)之类的内容,或者输入是否已重定向到文件等,则会发生这种情况。

To test if the input contains an integer and nothing but an integer, you can get input first into a string and then convert that with a stringstream. A stringstream indeed reaches eof if there's no more to be extracted from it.

要测试输入是否包含整数而仅包含整数,您可以先将输入输入到字符串中,然后使用字符串流将其转换。如果不再需要从字符串流中提取更多内容,则它确实会到达 eof。

#include <iostream>
#include <sstream>
#include <string>

int main() {
    using namespace std;
    int i;
    string input;
    cin >> input; //or getline(cin, input)
    stringstream ss(input);
    if (ss >> i && ss.eof()) {  //if conversion succeeds and there's no more to get
        cout<< "\n Correct Input \n";
    }
    else {
        cout<< "\n Format Error \n";
    }

  return 0;
}

回答by Bo Persson

Adding to the previous answer: After reading your input (like 10), you are not at end-of-file, as you can easily type some more. How is the system to know that you will not?

添加到上一个答案:阅读您的输入(如 10)后,您不在文件末尾,因为您可以轻松输入更多内容。系统怎么知道你不会?

When reading your second input (12a), it correctly reads all the digits that can be part of an integer. The letter 'a' cannot, so it is left for some possible later input. For example, you can read all parts of 12a with this code

在读取第二个输入 (12a) 时,它会正确读取可以作为整数一部分的所有数字。字母 'a' 不能,所以它留给以后可能的一些输入。例如,您可以使用此代码阅读 12a 的所有部分

int i; char c;

国际我; 字符 c;

cin >> i >> c;

cin >> i >> c;

回答by Karl Knechtel

EOF stands for end of file. std::cin is the standard input. The standard input, under normal circumstances, never reaches the end: you can always just type some more.

EOF代表ê第二Ø˚F ˚FILE。std::cin 是标准输入。在正常情况下,标准输入永远不会结束:您总是可以输入更多内容。

Further, .eof() only returns true if an input operation has already failed because of trying to read past the end of the file. The program actually can't tellthat it's "at the end of file"; that is, the only way it can find out that the next attempt to read data will fail is by actually making the attempt.

此外,.eof() 仅在输入操作因尝试读取文件末尾而失败时才返回 true 。程序实际上无法判断它是“在文件末尾”;也就是说,它可以发现下一次读取数据尝试将失败的唯一方法是实际进行尝试。