测试cin例外

时间:2012-10-05 21:46:40

标签: c++ ios exception cin

我应该在带有例外()的程序中测试输入。 我构造了以下代码,我可以编译而不会出错:

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

        }
        ...
     }while(...)

事情是......我不知道如何测试这段代码。我可以编写什么类型的输入来获取failbit或badbit?

1 个答案:

答案 0 :(得分:0)

根据此(Error states of streams)failbit在错误的输入序列时生成。例如,你写的东西如下: int n = 0; cin&gt;&gt; N;并输入字符串而不是数字。


    int main(void)
    {
        int n = 0;
        cin.exceptions(istream::failbit | istream::badbit);

        try
        {
            cin >> n;
        }
        catch(istream::failure e)
        {
            cerr << "Exception" << endl;

        }
        return 0;
    }

相关问题