C++ 从二进制文件和 failbit 中读取布尔值

C++ read boolean from binary file and failbit

我在用 C++ (visual studio 2015/windows) 从二进制文件中读取布尔值时遇到问题。在尝试读取布尔值之前,istream 是好的,但在读取之后设置了 failbit,而流不是 eof 并且 badbit 也没有设置。

关于 failbit 状态的一些文档: "Returns true in the same cases as bad(), but also in the case that a format error happens, like when an alphabetical character is extracted when we are trying to read an integer number."

基本上我不明白如果流之前是好的而不是 eof 之后从二进制流中读取布尔值怎么会失败。我的假设是,由于只有一位读作布尔值,因此没有格式。可能还有其他设置failbit的条件?

void Parser::binary2Record(std::istream& in) {
    bool is_next_booking;
    in >> current_record_;
    in >> is_next_booking;
    Segment segment;
    while (!is_next_booking && in) {
        in >> segment;
        current_record_.addSegment(segment);

        std::cout << "State of io before reading boolean " << (in.good() ? "Good" : "Not good") << std::endl;

        in >> is_next_booking;

        std::cout << "State of io good after reading boolean " << (in.good() ? "Good" : "Not good") << std::endl;
        std::cout << "State of io fail after reading boolean " << (in.fail() ? "fail" : "Not fail") << std::endl;
        std::cout << "State of io bad after reading boolean " << (in.bad() ? "Bad" : "Not Bad") << std::endl;
        std::cout << "State of io eof after reading boolean " << (in.eof() ? "Eof" : "Not eof") << std::endl;
    }
}

Output:
State of io before reading boolean Good
State of io good after reading boolean Not good
State of io fail after reading boolean fail
State of io bad after reading boolean Not Bad
State of io eof after reading boolean Not eof

My assumption is that since there is only one bit read as a boolean, there is no formatting.

这就是你的问题所在。 stream >> bool_var 进行 格式化 输入(它正在寻找字符 "true" 或 "false")。如果要进行无格式输入,则必须使用 stream.read()stream.get().

使用 ios_base::openmode::binary 的唯一一件事就是改变行尾字符的处理方式。