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
你应该'的std :: cin.ignore()'这无法读取的问题的性质。 –