uint8_t can't be printed with cout

前端 未结 8 2148

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 expe

8条回答
  •  花落未央
    2020-11-21 13:44

    As others said before the problem occurs because standard stream treats signed char and unsigned char as single characters and not as numbers.

    Here is my solution with minimal code changes:

    uint8_t aa = 5;
    
    cout << "value is " << aa + 0 << endl;
    

    Adding "+0" is safe with any number including floating point.

    For integer types it will change type of result to int if sizeof(aa) < sizeof(int). And it will not change type if sizeof(aa) >= sizeof(int).

    This solution is also good for preparing int8_t to be printed to stream while some other solutions are not so good:

    int8_t aa = -120;
    
    cout << "value is " << aa + 0 << endl;
    cout << "bad value is " << unsigned(aa) << endl;
    

    Output:

    value is -120
    bad value is 4294967176
    

    P.S. Solution with ADL given by pepper_chico and πάντα ῥεῖ is really beautiful.

提交回复
热议问题