【问题标题】:How to avoid Input a String in an Integer value using Try Catch (C++)如何避免使用 Try Catch (C++) 在整数值中输入字符串
【发布时间】:2015-01-08 16:20:27
【问题描述】:
我只是希望用户避免使用 Try Catch 在整数值中输入字符串,因为使用 while 循环根本不起作用。我知道如何在 Java 中使用 Try Catch,但我不会在 C++ 中使用。我一直在尝试这样的事情:
#include <iostream>
using namespace std;
main(){
int opc;
bool aux=true;
do{
try{
cout<<"PLEASE INSERT VALUE:"<<endl;
cin>>opc;
aux=true;
}
catch(int e){
aux=false;
throw e;
cout<<"PLEASE INSERT A VALID OPTION."<<endl;
}
}while(aux==false);
system("PAUSE");
}//main
【问题讨论】:
标签:
c++
validation
exception
input
try-catch
【解决方案1】:
int opc;
cin >> opc;
当您尝试读取非数字值时,将设置流的bad bit。您可以检查流是否处于良好状态。如果没有,请重置状态标志并根据需要再次尝试读取。请注意,当设置了坏位时,将忽略任何后续读取。所以在再次试用之前你应该做的是先清除输入流的坏位,然后忽略其余的坏输入。
// If the input stream is in good state
if (cin >> opc)
{
cout << opc << endl;
}
else
{
// Clear the bad state
cin.clear();
// Ignore the rest of the line
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
// Now if the user enters an integer, it'll be read
cin >> opc;
cout << opc << endl;
【解决方案2】:
有更简单更好的方法可以做到这一点,但如果你真的想要异常,你可以启用它们并捕获std::ios_base::failure。像这样的:
int main() {
int opc;
bool aux = true;
cin.exceptions(std::istream::failbit);
do {
try {
cout << "PLEASE INSERT VALUE:" << endl;
cin >> opc;
aux = true;
}
catch (std::ios_base::failure &fail) {
aux = false;
cout << "PLEASE INSERT A VALID OPTION." << endl;
cin.clear();
std::string tmp;
getline(cin, tmp);
}
} while (aux == false);
system("PAUSE");
}
【解决方案3】:
在正常情况下,当提供的数据不适合时,所有 istream 的 std::cin 不会抛出异常。流将其内部状态更改为 false。因此,您可以简单地执行以下操作:
int n;
std::cin >>n;
if(!std::cin) {
// last read failed either due to I/O error
// EOF. Or the last stream of chars wasn't
// a valid number
std::cout << "This wasn't a number" << std::endl;
}