uint8_t iostream行为 [英] uint8_t iostream behavior
问题描述
摘要:我期待的代码:cout< uint8_t(0);打印0,但它不打印任何东西。
Abstract: I was expecting the code: cout << uint8_t(0); to print "0", but it doesn't print anything.
长版本:当我尝试将uint8_t对象流化到cout时,这是预期的行为吗?可能是uint8_t是一些char类型的别名?请参阅代码示例中的编译器/系统注释。
Long version: When I try to stream uint8_t objects to cout, I get strange characters with gcc. Is this expected behavior? Could it be that uint8_t is an alias for some char-based type? See compiler/system notes in the code example.
// compile and run with:
// g++ test-uint8.cpp -std=c++11 && ./a.out
// -std=c++0x (for older gcc versions)
/**
* prints out the following with compiler:
* gcc (GCC) 4.7.2 20120921 (Red Hat 4.7.2-2)
* on the system:
* Linux 3.7.9-101.fc17.x86_64
* Note that the first print statement uses an unset uint8_t
* and therefore the behaviour is undefined. (Included here for
* completeness)
> g++ test-uint8.cpp -std=c++11 && ./a.out
>>>�<<< >>>194<<<
>>><<< >>>0<<<
>>><<< >>>0<<<
>>><<< >>>0<<<
>>><<< >>>1<<<
>>><<< >>>2<<<
*
**/
#include <cstdint>
#include <iostream>
void print(const uint8_t& n)
{
std::cout << ">>>" << n << "<<< "
<< ">>>" << (unsigned int)(n) << "<<<\n";
}
int main()
{
uint8_t a;
uint8_t b(0);
uint8_t c = 0;
uint8_t d{0};
uint8_t e = 1;
uint8_t f = 2;
for (auto i : {a,b,c,d,e,f})
{
print(i);
}
}
推荐答案
code> uint8_t 是 unsigned char
的别名,iostreams对于打印字符而不是格式化数字的字符有特殊重载。
uint8_t
is an alias for unsigned char
, and the iostreams have special overloads for chars that print out the characters rather than formatting numbers.
转换为整数会禁止此操作。
The conversion to integer inhibits this.
这篇关于uint8_t iostream行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!