std :: cin不会在输入错误时抛出异常 [英] std::cin doesn't throw an exception on bad input

查看:153
本文介绍了std :: cin不会在输入错误时抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是试图编写一个从cin读取的简单程序,然后验证输入是否为整数。如果是这样,我将退出while循环。如果没有,我将再次要求用户输入。

I am just trying to write a simple program that reads from cin, then validates that the input is an integer. If it does, I will break out of my while loop. If not, I will ask the user for input again.

我的程序可以编译并正常运行,这很棒。但是,如果我输入非数字值,它不会提示您输入新的内容。

My program compiles and runs just fine, which is great. But it doesn't prompt for new input if I enter a non numeric value. What gives?

#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;
}


推荐答案

C ++ iostream不使用除非您通过 cin.exceptions(/ *例外条件* /)

C++ iostreams don't use exceptions unless you tell them to, with cin.exceptions( /* conditions for exception */ ).

但是您的代码流程自然而然没有例外。只需执行 if(!(cin>>输入)),等等。

But your code flow is more natural without the exception. Just do if (!(cin >> input)), etc.

还记得清除

整个事情可能是:

int main()
{
    int input;
    do {
       cout << "Please enter an integral value \n";
       cin.clear();
       cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    } while(!(cin >> input));
    cout << input;
    return 0;
}

这篇关于std :: cin不会在输入错误时抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆