问题描述
我有一个关于在 C++ 中处理整数的奇怪问题.
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;
这个程序的输出是value is
即,它为 aa
打印空白.
I.e., it prints blank for aa
.
当我将 uint8_t
更改为 uint16_t
时,上面的代码就像一个魅力.
When I change uint8_t
to uint16_t
the above code works like a charm.
我使用 Ubuntu 12.04 (Precise Pangolin),64 位,我的编译器版本是:
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)
推荐答案
它并没有真正打印空白,但很可能是值为 5 的 ASCII 字符,它是不可打印的(或不可见的).有许多不可见的ASCII字符代码,其中大部分低于值32,实际上是空白.
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.
您必须将 aa
转换为 unsigned int
以输出数值,因为 ostream&operator< 尝试输出可见字符值.
You have to convert
aa
to unsigned int
to output the numeric value, since ostream& operator<<(ostream&, unsigned char)
tries to output the visible character value.
uint8_t aa=5;
cout << "value is " << unsigned(aa) << endl;
这篇关于uint8_t 不能用 cout 打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!