Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
677 views
in Technique[技术] by (71.8m points)

c++ - uint8_t can't be printed with cout

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)
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...