C++ struct数据成员

Les*_*ieg 5 c++ linux

我在C++,Linux工作,我遇到的问题如下:

struct testing{
uint8_t a;
uint16_t b;
char c;
int8_t d;

};

testing t;

t.a = 1;
t.b = 6;
t.c = 'c';
t.d = 4;
cout << "Value of t.a >>" << t.a << endl;
cout << "Value of t.b >>" << t.b << endl;
cout << "Value of t.c >>" << t.c << endl;
cout << "Value of t.d >>" << t.d << endl;
Run Code Online (Sandbox Code Playgroud)

我的控制台上的输出是:

Value of t.a >>
Value of t.b >>6
Value of t.c >>c
Value of t.d >>
Run Code Online (Sandbox Code Playgroud)

对于int8_t和uint8_t类型,似乎缺少ta和td.为什么会这样?

谢谢.

Fer*_*cio 10

int8_t和uint8_t类型可能被定义为char和unsigned char.流<<运算符将输出为字符.由于它们分别设置为1和4,它们是控制字符而不是打印字符,因此控制台上不会显示任何内容.尝试将它们设置为65和66('A'和'B'),看看会发生什么.

编辑:要打印出数字而不是字符,您需要将它们转换为适当的类型:

cout << static_cast<unsigned int>(t.a) << endl;
Run Code Online (Sandbox Code Playgroud)

  • ...或者将它们输出为`<< unsigned(ta)<<`和`<< unsigned(tb)<<` (2认同)