C++ cin.fail() 的正确使用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17928865/
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-27 21:34:32  来源:igfitidea点击:

Correct way to use cin.fail()

c++cin

提问by James Kanze

What is the correct way to use cin.fail();?

正确的使用方法是cin.fail();什么?

I am making a program where you need to input something. It is not very clear if you need to input a number or character. When a user inputs a character instead of a number the console goes crazy. How can I use cin.fail()to fix this?

我正在制作一个您需要输入内容的程序。是否需要输入数字或字符不是很清楚。当用户输入字符而不是数字时,控制台会发疯。我怎样才能cin.fail()解决这个问题?

Or is there a better way?

或者,还有更好的方法?

采纳答案by Shumail

cin.fail()returns true if the last cin command failed, and false otherwise.

cin.fail()如果最后一个 cin 命令失败,则返回 true,否则返回 false。

An example:

一个例子:

int main() {
  int i, j = 0;

  while (1) {
    i++;
    cin >> j;
    if (cin.fail()) return 0;
    cout << "Integer " << i << ": " << j << endl;  
  }
}

Now suppose you have a text file - input.txt and it's contents are:

现在假设你有一个文本文件 - input.txt,它的内容是:

  30 40 50 60 70 -100 Fred 99 88 77 66

When you will run above short program on that, it will result like:

当你运行上面的短程序时,结果如下:

  Integer 1: 30
  Integer 2: 40
  Integer 3: 50
  Integer 4: 60
  Integer 5: 70
  Integer 6: -100

it will not continue after 6th value as it quits after reading the seventh word, because that is not an integer: cin.fail()returns true.

它不会在第 6 个值之后继续,因为它在读取第 7 个单词后退出,因为它不是整数:cin.fail()返回true

回答by James Kanze

std::cin.fail()is used to test whether the preceding input succeeded. It is, however, more idiomatic to just use the stream as if it were a boolean:

std::cin.fail()用于测试前面的输入是否成功。然而,更习惯的做法是将流当作布尔值来使用:

if ( std::cin ) {
    //  last input succeeded, i.e. !std::cin.fail()
}

if ( !std::cin ) {
    //  last input failed, i.e. std::cin.fail()
}

In contexts where the syntax of the input permit either a number of a character, the usual solution is to read it by lines (or in some other string form), and parse it; when you detect that there is a number, you can use an std::istringstreamto convert it, or any number of other alternatives (strtol, or std::stoiif you have C++11).

在输入的语法允许多个字符的上下文中,通常的解决方案是按行(或以其他字符串形式)读取它,然后解析它;当您检测到有一个数字时,您可以使用 anstd::istringstream来转换它,或者使用任意数量的其他替代方法(strtol,或者 std::stoi如果您有 C++11)。

It is, however, possible to extract the data directly from the stream:

但是,可以直接从流中提取数据:

bool isNumeric;
std::string stringValue;
double numericValue;
if ( std::cin >> numericValue ) {
    isNumeric = true;
} else {
    isNumeric = false;
    std::cin.clear();
    if ( !(std::cin >> stringValue) ) {
        //  Shouldn't get here.
    }
}