我只是希望用户避免使用 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
最佳答案
有更简单和更好的方法来做到这一点,但如果你真的想要异常,你可以启用它们并捕获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");
}
关于c++ - 如何避免使用 Try Catch (C++) 在整数值中输入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26876396/