22

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

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

或者,还有更好的方法?

4

2 回答 2

22

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()
}

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

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

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.
    }
}
于 2013-07-29T16:22:28.670 回答
11

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

一个例子:

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

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

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

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

当您在上面运行短程序时,结果如下:

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

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

于 2013-07-29T16:23:30.097 回答