尝试检查cin是否获得了有效的输入(例如 - int变量中没有字符串或char),但是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
答案 0 :(得分: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;
}