uint8_t can't be printed with cout

前端 未结 8 2151

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 14:03

    The operator<<() overload between istream and char is a non-member function. You can explicitly use the member function to treat a char (or a uint8_t) as an int.

    #include <iostream>
    #include <cstddef>
    
    int main()
    {
       uint8_t aa=5;
    
       std::cout << "value is ";
       std::cout.operator<<(aa);
       std::cout << std::endl;
    
       return 0;
    }
    

    Output:

    value is 5
    
    0 讨论(0)
  • 2020-11-21 14:05

    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;
    
    0 讨论(0)
提交回复
热议问题