How can I print to the console in color in a cross-platform manner?

前端 未结 3 1030
终归单人心
终归单人心 2020-12-04 15:32

How can I output colored text using \"printf\" on both Mac OS X and Linux?

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-04 16:17

    You can use the ANSI colour codes. Here's an example program:

    #include 
    
    int main(int argc, char *argv[])
    {
      printf("%c[1;31mHello, world!\n", 27); // red
      printf("%c[1;32mHello, world!\n", 27); // green
      printf("%c[1;33mHello, world!\n", 27); // yellow
      printf("%c[1;34mHello, world!\n", 27); // blue
      return 0;
    }
    

    The 27 is the escape character. You can use \e if you prefer.

    There are lists of all the codes all over the web. Here is one.

提交回复
热议问题