【问题标题】:std::cin doesn't throw an exception on bad inputstd::cin 不会对错误输入抛出异常
【发布时间】:2014-11-29 00:43:46
【问题描述】:

我只是想编写一个从 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;
}

【问题讨论】:

标签: c++ visual-studio-2012 error-handling


【解决方案1】:

C++ iostream 不使用异常,除非你用cin.exceptions( /* conditions for exception */ ) 告诉它们。

但是你的代码流更自然,没有例外。只要做if (!(cin &gt;&gt; input))等。

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

整个事情可以是:

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

【讨论】:

  • 谢谢,我习惯了Java。我已经更新了我的问题,我的循环仍然没有中断?
  • @AdamJ:对于input 是否为整数,没有有意义的测试。不,真的,它的数据类型禁止它成为其他任何东西。核对 if (!( input % 1 ) || input == 0)if (( input / 1 != input ) || (input == 0)) 或任何你梦想的东西。 input 是一个整数。即使用户键入了不是整数的内容,input 也是一个整数——并且cin 被标记为失败,您可以从if (!cin)while (!cin) 了解这一点
【解决方案2】:

不要使用using namespace std; 而是导入你需要的东西。

最好一次输入一行。如果您在一行中有多个单词,或者如果您在输入任何内容之前按回车键,这会使行为更加更加直观。

#include <iostream>
#include <sstream>
#include <string>

using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::flush;
using std::getline;
using std::istringstream;
using std::string;

int main() {
    int input;
    while (true)
    {
        cout << "Please enter an integral value: " << flush;
        string line;
        if (!getline(cin, line)) {
            cerr << "input failed" << endl;
            return 1;
        }
        istringstream line_stream(line);
        char extra;
        if (line_stream >> input && !(line_stream >> extra))
            break;
    }
    cout << input << endl;
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 1970-01-01
    • 2022-08-08
    • 1970-01-01
    相关资源
    最近更新 更多