我有一个问题,能够处理运行时错误,其中用户输入的数据不同于预期的数据。例如,一个整数是预期的,但(可能)用户输入一个字符串。在我的控制台程序中,发生这种情况时,我只是在屏幕上打印了大量垃圾,它进入了无限循环。我该如何处理这个问题,以便在发生这种情况时显示一条错误消息,而不是整个程序都会出现垃圾?如何在C++中捕获运行时错误?
int x = 0;
cout << "\n\nEnter a number(1-9): ";
cin >> x;
if(x<1 || x>9)
{
cout<<"\nThe place you entered is invalid. Please enter the correct place number";
}else{
cout<<"Correct";
}
如果我进入上述大于2^31(我知道其为int数据类型的最大值)或它进入一个无限循环char值的数字。我怎样才能搭上解决这个problme
这是一个重复的:http://stackoverflow.com/questions/545907/what-is-the-best-way-to-do-input-validation-in-c-with-cin – 2012-03-31 18:33:49