本文介绍了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
";
            cin >> input;
            if (!( input % 1 ) || input == 0){ break; }
        }
        catch (exception& e)
        { cout << "Please enter an integral value";
        flag = true;}
    }
    cout << input;
    return 0;
}

推荐答案

C++ iostreams 不使用异常,除非你告诉他们使用 cin.exceptions(/* 异常条件 */).

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

但是您的代码流更自然,无一例外.只需执行 if (!(cin >> input))

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

还要记得在重试之前清除失败位.

Also remember to clear the failure bit before trying again.

整个事情可以是:

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

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

08-21 12:49