C++;从二进制文件和故障位读取布尔值 我面临的问题是从C++中的二进制文件(Visual Studio 2015/Windows)中读取布尔值。在尝试读取布尔值之前,istream是良好的,但在读取后,设置了failbit,而流不是eof,也没有设置badbit

C++;从二进制文件和故障位读取布尔值 我面临的问题是从C++中的二进制文件(Visual Studio 2015/Windows)中读取布尔值。在尝试读取布尔值之前,istream是良好的,但在读取后,设置了failbit,而流不是eof,也没有设置badbit,c++,io,binary,iostream,C++,Io,Binary,Iostream,关于故障位状态的一些文档: 在与bad()相同的情况下返回true,但在发生格式错误的情况下也返回true,例如在尝试读取整数时提取字母字符 基本上,我不明白,如果二进制流之前是好的,而之后不是eof,那么从二进制流读取布尔值怎么可能失败。我的假设是,因为只有一位被读取为布尔值,所以没有格式。可能存在设置故障位的其他条件 void Parser::binary2Record(std::istream& in) { bool is_next_booking; in >

关于故障位状态的一些文档: 在与bad()相同的情况下返回true,但在发生格式错误的情况下也返回true,例如在尝试读取整数时提取字母字符

基本上,我不明白,如果二进制流之前是好的,而之后不是eof,那么从二进制流读取布尔值怎么可能失败。我的假设是,因为只有一位被读取为布尔值,所以没有格式。可能存在设置故障位的其他条件

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
void解析器::binary2Record(std::istream&in){
布尔是下一个预订;
在>>当前\u记录\u;
在>>中是下一个预订;
段;
当(!是下一个预订(&U)时{
在>>部分;
当前记录添加段(段);
标准::cout
我的假设是,因为只有一位被读取为布尔值,所以没有格式

这就是问题所在。
stream>>bool\u var
进行格式化输入(它正在查找字符“true”或“false”)。如果要进行无格式输入,必须使用
stream.read()
stream.get()


使用
ios\u base::openmode::binary
的唯一功能是改变行尾字符的处理方式。

它真的存在吗?您没有检查eof或任何东西。您不能使用格式化文本提取来读取二进制数据。