我试图找到用户输入的值是String或Int,但是当用户输入任何字符串时程序卡在循环中。如果是,那么我删除int taxableIncome
值一次执行然后如何?
我是初级程序员......
无论如何我告诉我,我可以检查用户的值是int还是string ....
这是代码
int taxableIncome;
for (;;) {
cout << "Please enter in your taxable income: ";
if (cin >> taxableIncome) {
cout << "Your income: " << taxableIncome;
break;
} else {
cout << "Please enter a valid integer" << endl;
}
}
答案 0 :(得分:3)
cin >> taxableIncome
失败后(您正在检测)cin
的进一步读取将直接失败,因为该流已标记其bad
位。你需要清除那一点,咀嚼剩余的线,然后再试一次。
int taxableIncome;
for (;;) {
cout << "Please enter in your taxable income: ";
if (cin >> taxableIncome) {
cout << "Your income: " << taxableIncome;
break;
} else {
cout << "Please enter a valid integer" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}