iostream clear()

北城以北 提交于 2019-12-06 13:29:45

问题


istream &func(istream &in)
{
    string data;

    while (in >> data, !in.eof()) {
        if (in.bad())
            throw runtime_error("IO stream corrupted");
        if (in.fail()) {
            cerr << "bad data, try again" << endl;
            in.clear();
            in.ignore(200);
            continue;
        }   

        cout << data << endl;;
    }   

    //in.clear(istream::eofbit | istream::failbit);
    in.clear();

    return in; 
}

why in.clear(istream::eofbit | istream::failbit); can not reset the cin?

but in.clear can make it.

PS: I use this function in main(), and use cin as its parameter.


回答1:


clear is defined like this:

void clear(iostate state = goodbit);

So, effectively, in.clear(); is doing this: in.clear(istream::goodbit); which resets the stream. Calling in.clear(istream::eofbit | istream::failbit); would set both the eofbit and failbit, I doubt that is what you want.

std::cin.clear(std::istream::eofbit | std::istream::failbit);
std::ios_base::iostate state = std::cin.rdstate();
if( state == (std::istream::eofbit | std::istream::failbit))
{
    std::cout << "eofbit and failbit set" << std::endl;
}


来源:https://stackoverflow.com/questions/10877275/iostream-clear

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