我似乎无法弄清楚为什么在获得非int输入后它会陷入循环.我已经尝试了cin.flush(),它似乎不存在,cin.clear(),它看起来应该可以工作,甚至cin.sync()在阅读其他人发布有关它工作后,但没有似乎很有意义.还尝试了cin.bad().
非常感谢您的帮助
请输入第一个数字:f对不起,我不认为这是一个数字?
请输入第一个号码:对不起,我不认为这是一个号码?
请输入第一个号码:对不起,我不认为这是一个号码?
请输入第一个号码:对不起,我不认为这是一个号码?
请输入第一个号码:对不起,我不认为这是一个号码?对不起,你再也没有尝试了.按任意键继续 ...
#include <iostream>
using namespace std;
int main(){
int entry;
int attempts = 1;
int result;
while(attempts <= 5) {
try {
cout << "\n\nPlease enter the first number: ";
cin >> entry;
if (cin.fail())
throw "Sorry, I don't think that's a number?";
if (entry < 0)
throw "Sorry, no negative numbers. Try something else? ";
cout << "\nNow the second number: ";
cin >> entry;
cin.clear();
cin.get();
}
catch (char* error) { …Run Code Online (Sandbox Code Playgroud)