uint8_t can't be printed with cout

2018-12-31 04:04发布

I have a weird problem about working with integers in C++.

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 aa = 5;

cout << "value is " << aa << endl;

The output of this program is value is

I.e., it prints blank for aa.

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)

标签: c++
8条回答
无与为乐者.
2楼-- · 2018-12-31 04:22

The operator<<() overload between istream and char is a non-member function. You can explicitly use the member function to treat a char (or a uint8_t) as an int.

#include <iostream>
#include <cstddef>

int main()
{
   uint8_t aa=5;

   std::cout << "value is ";
   std::cout.operator<<(aa);
   std::cout << std::endl;

   return 0;
}

Output:

value is 5
查看更多
柔情千种
3楼-- · 2018-12-31 04:29

It's because the output operator treats the uint8_t like a char (uint8_t is usually just an alias for unsigned char), so it prints the character with the ASCII code (which is the most common character encoding system) 5.

See e.g. this reference.

查看更多
登录 后发表回答