可能重复:
How to validate numeric input C++检查C++字符串一个int:修改为:结算CIN
你如何做到以下几点:
while (iNumberOfPlayers <2 || iNumberOfPlayers >5)
{
cout << "Enter number of players (1-4): ";
cin >> iNumberOfPlayers;
cin.clear();
std::string s;
cin >> s;
}
看后循环我投入,它看起来像cin
没有得到重置(如果我把x)只要我在while
循环中,3210就会再次读取X.猜测这是一个缓冲区问题,有什么方法可以清除它?
我然后设法:
while (iNumberOfPlayers <2 || iNumberOfPlayers >5)
{
cout << "Enter number of players (1-4): ";
cin >> iNumberOfPlayers;
cin.clear();
cin.ignore();
}
除了它其中工程一次读取都1。如果我输入“xyz”,那么循环会经过3次,然后再停下来再次提问。
你需要声明,比如'INT一= 0;' – ThomasMcLeod 2012-07-14 14:46:35
但是,如果你将'a'声明为int,那么是不是很难成为一个int? – 2012-07-14 14:47:11
@SimonAndréForsbergint a = 0; cin << a;如果有人放入一些不是int的东西(例如x),整个程序就会崩溃。 – 2012-07-14 14:49:07