Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 728
Mike Avatar asked Mar 01 '10 01:03

Mike


People also ask

How do I change the color of my console in C++?

Use SetConsoleTextAttribute() Method to Change Console Color in C++ SetConsoleTextAttribute is the Windows API method to set output text colors using different parameters. This function sets the attributes of characters written to the console screen buffer by the WriteFile or WriteConsole functions.


1 Answers

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

#include <stdio.h>      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.

like image 78
Carl Norum Avatar answered Oct 02 '22 12:10

Carl Norum