qdii
qdii

Reputation: 12963

Why is failbit() set?

Create a file and fill it up with zeroes:

dd if=/dev/zero of=/tmp/zeroes count=1

Write this little program to extract the first unsigned integer it encounters in the file.

#include <assert.h>
#include <fstream>

int main()
{
    std::ifstream reader( "/tmp/zeroes", std::ios_base::binary );
    uint32_t number;
    reader >> number;

    assert( !reader.fail() );
}

Why is the assert triggered?

Upvotes: 4

Views: 373

Answers (1)

James Kanze
James Kanze

Reputation: 153909

Because /dev/zero delivers binary zeros, not the character '0', and >> does (or tries to do) a conversion from text.

Upvotes: 8

Related Questions