【发布时间】:2017-02-25 04:21:19
【问题描述】:
尝试检查 cin 是否获得了有效输入(例如 - int 变量中没有字符串或字符),但 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()无法读取的违规字符。
标签: c++