试图检查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
1 回答
应用
cin.clear();
之后,您需要首先使用错误的输入,然后再次应用cin >> buyAmt;
.就像是