【问题标题】:Test cin exception测试cin异常
【发布时间】:2012-09-27 02:18:06
【问题描述】:

我应该在带有异常()的程序中测试输入。 我已经构建了以下代码,并且可以无错误地编译:

cin.exceptions(istream::failbit |istream::badbit);
    do
    {
        try
        {
            getline(cin,uppg);
        }
        catch(istream::failure e)
        {
            cerr << "Exception i inläsning";

        }
        ...
     }while(...)

问题是......我不知道如何测试这段代码。我可以写什么类型的输入来获得故障位或坏位?

【问题讨论】:

  • 你想测试什么?如果你想测试你的异常处理代码,你可以调用cin.setstate(istream::failbit),这将导致一个异常被抛出。

标签: c++ ios exception cin


【解决方案1】:

根据这个 (Error states of streams) 故障位在错误的输入序列时生成。例如,您编写如下内容: 诠释 n = 0;辛 >> n;并输入字符串而不是数字。

int main(void) { int n = 0; cin.exceptions(istream::failbit | istream::badbit); try { cin >> n; } catch(istream::failure e) { cerr &lt&lt "Exception" &lt&lt endl; } return 0; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-07
    • 2011-01-28
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多