2012-07-14 20 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'); 
    } 
}