2012-07-14 48 views
1

可能重复:
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次,然后再停下来再次提问。

+1

你需要声明,比如'INT一= 0;' – ThomasMcLeod 2012-07-14 14:46:35

+2

但是,如果你将'a'声明为int,那么是不是很难成为一个int? – 2012-07-14 14:47:11

+0

@SimonAndréForsbergint a = 0; cin << a;如果有人放入一些不是int的东西(例如x),整个程序就会崩溃。 – 2012-07-14 14:49:07

回答

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"; 
} 

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

+0

这不起作用,如果我输入“hello”,那么它会一直重复“值不是数字”,因为'cin.clear()'离开了输入中的字符串。在重复之前,您还需要使用非'int'输入。 – Flexo 2012-07-14 15:02:46

+1

@Flexo:您的评论通过我的编辑在互联网上的某处。现在应该工作。 – 2012-07-14 15:06:06

3

棘手的是,您需要使用任何无效输入,因为失败读取不会消耗输入。这个最简单的解决方案是将呼叫转移到operator >>进入循环状态,然后读取直到\n如果没有奶源读取一个int

#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'); 
    } 
}