2016-10-15 111 views
0

嘗試檢查cin是否獲得有效輸入(例如 - 沒有字符串或字符變量中的字符),但while循環卡住在一個無限循環,並沒有即使等待用戶輸入雖然循環不等待用戶輸入(雖然數據類型無效)

#include <iostream> 
#include <string> 
using namespace std; 
int main(){ 
    cout << "How many would you like to buy ? "; 
    int buyAmt; 
    cin >> buyAmt; 
    while (!cin) { 
     cin.clear(); 
     cin >> buyAmt; 
     cout << "Sorry, you must enter an integer" << endl << endl; 
    } 
} 

預期結果:

How many would you like to buy ? fdssd 
Sorry, you must enter an integer (asks for usr input here) 

實際結果:

How many would you like to buy ? fdssd 
Sorry, you must enter an integer 
Sorry, you must enter an integer 
Sorry, you must enter an integer 
Sorry, you must enter an integer 
Sorry, you must enter an integer 
Sorry, you must enter an integer 
+1

你應該'的std :: cin.ignore()'這無法讀取的問題的性質。 –

回答

2

後應用cin.clear();您需要先消耗錯誤的輸入,然後再次應用cin >> buyAmt;

喜歡的東西

while (!cin) { 
    std::string dummy; 
    cin.clear(); 
    cin >> dummy; 
    cout << "Sorry, you must enter an integer" << endl << endl; 
    cout << "How many would you like to buy ? "; 
    cin >> buyAmt; 
}