c++ - 如何避免使用 Try Catch (C++) 在整数值中输入字符串

标签 c++ validation exception input try-catch

我只是希望用户避免使用 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/

相关文章:

java - 控制 - Java 中的 C 异常

c++ - 字符串或 vector 类型为何不安全?

validation - 哪个更好? 403 状态代码或 422 状态代码以及验证和身份验证失败的负载?

c# - 引发登录/注册错误的异常是否合适?

jQuery 验证错误消息放置

java - 如何验证在 ja​​va swing 中只接受 float /十进制值的 jtextfield?

java - Java : when isn't a custom message "good enough"? 中的子类化异常

java - 是否每次都在for循环的condition语句中执行函数?

c++ - 如何在Qt中使用FontAwesome

c++ - 预编译 header 是否可以比干净构建的经典包含慢?