【问题标题】:checking C++ string for an int: revised: clearing cin [duplicate]检查 C++ 字符串的 int:修订:清除 cin [重复]
【发布时间】:2012-07-14 14:43:39
【问题描述】:

可能重复:
How to validate numeric input C++

你如何做到以下几点:

while (iNumberOfPlayers <2 || iNumberOfPlayers >5)
{
    cout << "Enter number of players (1-4): ";
    cin >> iNumberOfPlayers;
    cin.clear();
    std::string s;
    cin >> s;
}

在查看了我陷入的循环之后,看起来cin 没有被重置(如果我输入 x)只要我在 while 循环中,cin 就会再次读取 X .猜测这是缓冲区问题,有什么办法可以清除它?

然后我尝试了:

while (iNumberOfPlayers <2 || iNumberOfPlayers >5)
{
    cout << "Enter number of players (1-4): ";
    cin >> iNumberOfPlayers;
    cin.clear();
    cin.ignore();
}

除了一次读取所有内容 1 之外,它可以工作。如果我输入“xyz”,那么循环会经过 3 次才停止再次询问。

【问题讨论】:

  • 你需要声明一个,比如int a = 0;
  • 但是如果你将a声明为一个int,那不是让a很难成为一个int吗?
  • @SimonAndréForsberg int a = 0;辛
  • Matt,您的帖子标题询问是否可以将字符串测试为 int,但您的代码中没有字符串。 cin 不会自动将内容读取为字符串。我刚刚测试了输入不良数据,“a”仍然是“0”。
  • @Matt:不,如果程序崩溃是因为有人输入了非数字数据,那是因为你的代码没有检查输入是否失败。 stream 在尝试解析无效输入时不会crash

标签: c++ string int cin


【解决方案1】:

如果输入无效,则在流上设置失败位。流上使用的! 运算符读取失败位(您也可以使用(cin &gt;&gt; a).fail()(cin &gt;&gt; a), cin.fail())。

那么你只需要在重试之前清除失败位。

while (!(cin >> a)) {
    // if (cin.eof()) exit(EXIT_FAILURE);
    cin.clear();
    std::string dummy;
    cin >> dummy; // throw away garbage.
    cout << "entered value is not a number";
}

请注意,如果您从非交互式输入中读取,这将成为一个无限循环。因此,对注释过的错误检测代码使用一些变体。

【讨论】:

  • 这不起作用,如果我输入“你好”,那么它会不断重复“值不是数字”,因为cin.clear() 将字符串留在输入中。在重复之前,您还需要消耗非int 输入。
  • @Flexo:您的评论跨越了我在互联网某处的编辑。现在应该可以工作了。
【解决方案2】:

棘手的是您需要消耗任何无效输入,因为读取失败不会消耗输入。最简单的解决方案是将调用 operator &gt;&gt; 移动到循环条件中,然后如果无法读取 int,则读取到 \n

#include <iostream>
#include <limits>

int main() {
  int a;
  while (!(std::cin >> a) || (a < 2 || a > 5)) {
    std::cout << "Not an int, or wrong size, try again" << std::endl;
    std::cin.clear(); // Reset error and retry
    // Eat leftovers:
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  }
}

【讨论】:

    猜你喜欢
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    • 1970-01-01
    • 2013-09-14
    • 2017-03-25
    • 1970-01-01
    相关资源
    最近更新 更多