检查int的C++字符串:modified:clearing cin

Mat*_*ake 1 c++ string int cin

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

你如何做到以下几点:

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

在看完循环之后,看起来cin没有重置(如果我放入x)cin只要我在while循环中再次读取X. 猜测这是一个缓冲问题,有什么方法可以清除它?

然后我尝试了:

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

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

Ben*_*igt 7

如果输入无效,则在流上设置失败位.!流上使用的运算符读取失败位(您也可以使用(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";
}
Run Code Online (Sandbox Code Playgroud)

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