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
279 views
in Technique[技术] by (71.8m points)

c++ - uint8_t iostream behavior

Abstract: I was expecting the code: cout << uint8_t(0); to print "0", but it doesn't print anything.

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) << "<<<
";
}

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);
    }
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...