uint8_t can't be printed with cout

前端 未结 8 2149

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

    • Making use of ADL (Argument-dependent name lookup):

      #include 
      #include 
      #include 
      
      namespace numerical_chars {
      inline std::ostream &operator<<(std::ostream &os, char c) {
          return std::is_signed::value ? os << static_cast(c)
                                             : os << static_cast(c);
      }
      
      inline std::ostream &operator<<(std::ostream &os, signed char c) {
          return os << static_cast(c);
      }
      
      inline std::ostream &operator<<(std::ostream &os, unsigned char c) {
          return os << static_cast(c);
      }
      }
      
      int main() {
          using namespace std;
      
          uint8_t i = 42;
      
          {
              cout << i << endl;
          }
      
          {
              using namespace numerical_chars;
              cout << i << endl;
          }
      }
      

      output:

      *
      42
      
    • A custom stream manipulator would also be possible.

    • The unary plus operator is a neat idiom too (cout << +i << endl).

提交回复
热议问题