相关疑难解决方法(0)

std :: cin不会在输入错误时抛出异常

我只是想编写一个从cin读取的简单程序,然后验证输入是一个整数.如果确实如此,我将打破我的while循环.如果没有,我会再次要求用户输入.

我的程序编译并运行得很好,这很棒.但是如果输入非数字值,它不会提示输入新内容.是什么赋予了?

#include <iostream>
using namespace std;

int main() {
    bool flag = true;
    int input;
    while(flag){
        try{ 
            cout << "Please enter an integral value \n";
            cin >> input;
            if (!( input % 1 ) || input == 0){ break; }
        }
        catch (exception& e)
        { cout << "Please enter an integral value"; 
        flag = true;}
    }
    cout << input;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ error-handling visual-studio-2012

1
推荐指数
1
解决办法
2887
查看次数

标签 统计

c++ ×1

error-handling ×1

visual-studio-2012 ×1