c++ 正在清除流上的故障位

kpbpu008  于 2022-12-15  发布在  其他
关注(0)|答案(2)|浏览(131)

I'm using istream::get() to read characters from a stream. The issue is that when you read the EOF character, get sets the failbit.
I want to keep the stream clean, because there really hasn't been an error, but I do want to keep the eofbit set.
How do you keep the current state of the stream, but unset the failbit. I'm having issues understanding the differences between setstate and clear and how to use them to "unset" a bit on the stream.

klr1opcd

klr1opcd1#

To remove a single flag some the streams state is a two part process. First you need to get that current state of the stream with rdstate() and then do bitwise operations on that returned state to clear the flags you want. Then you can call clear() and pass the new state to that to have it set the state of the stream. You can see all of this working with this live example :

int main()
{
    std::cin.setstate(std::ios_base::failbit | std::ios_base::eofbit);

    std::cout << "before:\n";

    if (std::cin.fail()) {
        std::cout << "now cin is in fail state\n";
    }
    if (std::cin.eof()) {
        std::cout << "now cin is in eof state\n";
    }

    auto state = std::cin.rdstate();   // get state
    state &= ~std::ios_base::failbit;  // remove failbit from it
    std::cin.clear(state);             // clear old state and set new state

    std::cout << "\nafter:\n";

    if (std::cin.fail()) {
        std::cout << "now cin is in fail state\n";
    }
    if (std::cin.eof()) {
        std::cout << "now cin is in eof state\n";
    }
}

output:

before:
now cin is in fail state
now cin is in eof state

after:
now cin is in eof state
aiazj4mn

aiazj4mn2#

想明白了。我相信这是正确的方法:

int main()
{
     std::cin.setstate(std::ios_base::failbit | std::ios_base::eofbit);

     // new state is current state, with failbit removed
     auto state = std::cin.rdstate() & ~std::ios_base::failbit;

     // sets all of the flags
     std::cin.clear(state);   
}

相关问题