检查C++字符串中的整数:已修订:清除 cin
checking C++ string for an int: revised: clearing cin
可能的重复项:
如何验证数字输入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');
}
}
相关文章:
- C++中的cin.ignore()函数不适用于整个流
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- Problems with std::cin.fail()
- 清除前检查矢量
- 由cin中的字符串中未捕获空白引起的分割错误
- 在C++中使用Cin,我如何在1行中输入
- ifstream文件在从行中读取时被清除
- std::cin 在读取 EOF 并清除后不再读取
- 在C 中清除CIN
- cin.clear() 如何清除输入缓冲区
- 如何清除cin读取的内容
- 检查C++字符串中的整数:已修订:清除 cin
- 为什么我的编译器在尝试清除 CIN 缓冲区时抱怨
- 当用户输入错误输入时,一次清除 cin 中的整行而不是一个字符
- 使用GetAsyncKeyState()时,C++正在清除cin缓冲区
- cin.ignore(INT_MAX)正在清除所有内容
- 不停止,清除cin创建无限循环
- 使用cin对象进行输入验证并清除缓冲区(c++)
- 检查输入的值是否为float,清除cin
- 如何从cin中清除无关字符