Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is failbit() set?

Tags:

c++

istream

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?

like image 470
qdii Avatar asked Feb 13 '23 06:02

qdii


1 Answers

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

like image 113
James Kanze Avatar answered Feb 23 '23 08:02

James Kanze