2016-10-15 72 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; 
}