Colored output in C++

前端 未结 3 1999
后悔当初
后悔当初 2021-02-01 04:39

Is there a way to print colored output using iostream and Xcode? I\'d like to be able to, for example, print Hello World! with Hello red,

3条回答
  •  再見小時候
    2021-02-01 05:28

    In a more c++ way for an ANSI capable terminal, it is possible to write your own ansi stream manipulators like std::endl but for handling ansi escape code.

    Code for doing so can look like this for basic raw implementation:

    namespace ansi {
      template < class CharT, class Traits >
      constexpr
      std::basic_ostream< CharT, Traits > & reset( std::basic_ostream< CharT, Traits > &os )
      {
         return os << "\033[0m";
      }
    
      template < class CharT, class Traits >
      constexpr
      std::basic_ostream< CharT, Traits > & foreground_black( std::basic_ostream< CharT, Traits > &os )
      {
         return os << "\033[30m";
      }
    
      template < class CharT, class Traits >
      constexpr
      std::basic_ostream< CharT, Traits > & foreground_red( std::basic_ostream< CharT, Traits > &os )
      {
         return os << "\033[31m";
      }
      ...
     } // ansi
    

    And it can be used in a code like this:

    std::cout << ansi::foreground_red << "in red" << ansi::reset << std::endl;
    

提交回复
热议问题