检查C++字符串中的整数:已修订:清除 cin

checking C++ string for an int: revised: clearing cin

本文关键字:清除 cin 整数 C++ 字符串 检查      更新时间:2023-10-16

可能的重复项:
如何验证数字输入C++

您如何执行以下操作:

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

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

然后我尝试:

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

除了它一次读取 1 个所有内容外,它有效。 如果我输入"xyz",那么循环会经过 3 次,然后停止再次询问。

如果输入无效,则在流上设置故障位。 流上使用的!运算符读取故障位(您也可以使用 (cin >> a).fail()(cin >> 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";
}

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

棘手的是,您需要使用任何无效的输入,因为读取失败不会消耗输入。最简单的解决方案是将调用移动到循环条件中,如果读取int,则读取operator >>的调用,然后读取到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');
  }
}