如何在C ++中清除iostream对象中的状态位? [英] How to clear the state bits in an iostream object in C++?

查看:84
本文介绍了如何在C ++中清除iostream对象中的状态位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从Primer的较早版本中学习C ++,并尝试执行与iostream对象有关的一些代码,这给我带来了一些麻烦:

I'm trying to learn C++ from an older edition of the Primer, and tried to execute some of their code relating to iostream objects, which gave me some trouble:

#include <iostream>
#include <cstdlib>
using namespace std;

int main(int argc, char *argv[])
{
    int ival;

    try
    {
        while (cin >> ival, !cin.eof())
        {
            if (cin.bad())
                throw runtime_error("IO stream corrupted");
            if (cin.fail())
            {
                cerr << "Invalid input - try again";
                cin.clear(iostream::failbit);
                continue;
            }
            else
                cout << ival << endl;
        }

        return EXIT_SUCCESS;
    }

    catch(runtime_error err)
    {
        cout << err.what();
        return EXIT_FAILURE;
    }
}

当该程序遇到无效输入时,它将输出无效输入-重试"而不会停止,表示cin.clear(iostream::failbit)实际上并未清除" cin的故障位.我也尝试仅使用cin.clear()无济于事.所以我的问题是,如何使cin返回非错误状态?

When this program encounters an invalid input, it outputs "Invalid input - try again" without stopping, signaling that cin.clear(iostream::failbit) doesn't actually "clear" cin's failbit. I also tried just using cin.clear() to no avail. So my question is, how do I return cin to a non-error state?

推荐答案

如果我没记错的话,cin.clear(iostream :: failbit)会将新状态设置为失败.您应该首先消除引起问题的那部分输入,然后使用cin.clear()cin.clear(iostream::goodbit).

If I'm not mistaken, cin.clear(iostream::failbit) sets the new state to fail. You should first get rid of that part of the input that is causing the problems and then use cin.clear() or cin.clear(iostream::goodbit).

有关更多信息,请参见此处: http://www.cplusplus.com/reference/ios/ios/clear/

For more information, look here: http://www.cplusplus.com/reference/ios/ios/clear/

这篇关于如何在C ++中清除iostream对象中的状态位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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