How to clear the state bits in an iostream object in C++?

☆樱花仙子☆ 提交于 2020-04-30 07:49:11

问题


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

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?


回答1:


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).

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



来源:https://stackoverflow.com/questions/17012270/how-to-clear-the-state-bits-in-an-iostream-object-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!