c++coutunsigned-charuint8tc++-faq

uint8_t can't be printed with cout


I wrote a simple program that sets a value to a variable and then prints it, but it is not working as expected. My program has only two lines of code:

uint8_t a = 5;

cout << "value is " << a << endl;

The output of this program is value is , i.e., it prints blank for a.

When I change uint8_t to uint16_t, the above code works like a charm.

I use UbuntuĀ 12.04 (Precise Pangolin), 64-bit, and my compiler version is:

gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)

Solution

  • It doesn't really print a blank, but most probably the ASCII character with value 5, which is non-printable (or invisible). There's a number of invisible ASCII character codes, most of them below value 32, which is the blank actually.

    You have to convert a to unsigned int to output the numeric value, since ostream& operator<<(ostream&, unsigned char) tries to output the visible character value.

    uint8_t a = 5;
    
    cout << "value is " << unsigned(a) << endl;