C ++从二进制文件和failbit

时间:2016-12-22 08:51:11

标签: c++ io binary iostream

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

有关failbit的一些文档说明: “在与bad()相同的情况下返回true,但在发生格式错误的情况下也是如此,例如在我们尝试读取整数时提取字母字符时。”

基本上我不明白如果流之前是好的而不是之后的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

1 个答案:

答案 0 :(得分:0)

  

我的假设是,由于只有一位读取为布尔值,因此没有格式化。

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

唯一使用ios_base::openmode::binary的方法是更改​​行尾字符的处理方式。