DEV Community

Cover image for Terminal colors in C/C++
Tenry
Tenry

Posted on

Terminal colors in C/C++

When developing cross-platform terminal applications or using terminal output for logging or debugging, it's useful to color the output in order to not lose the overview.

This article shows how to color the terminal output on various platforms.

Linux

On Linux, you can change the current foreground and background color by writing special character sequences into the output. Write the ESC escape character (octal "\033", hex \x1b), followed by an opening square bracket [. The color definition will follow next, termniated by a lowercase m.

The color definition is a series of numbers, separated by semicolons. In order to make the text color red (number 31), you can write "\033[31m" which will make any following output red. If you want yellow text (33) on blue background (44), you write "\033[31;44m". To reset everything back to the default colors, you write "\033[0m".

#include <stdio.h>

void main() {
  printf("\033[31mred text\n");
  printf("\033[33;44myellow on blue\n");
  printf("\033[0mdefault colors\n");
}
Enter fullscreen mode Exit fullscreen mode

The terminal-colors.d manual gives you an overview over the available codes.

Windows

On Windows, coloring the terminal output, works a bit different. Instead of writing special character sequences into the output, you have to call special functions from the windows library. #include <windows.h> in order to access the Windows functions. This provides the SetConsoleTextAttribute() function that can be used to color the text. You also need to get a handle to the stdout console using GetStdHandle(STD_OUTPUT_HANDLE).

The following code shows how to color the text red and yellow on blue background:

#include <stdio.h>
#include <windows.h>

void main() {
  HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

  SetConsoleTextAttribute(hConsole,
    FOREGROUND_RED);
  printf("red text\n");

  SetConsoleTextAttribute(hConsole,
    FOREGROUND_RED | FOREGROUND_GREEN | BACKGROUND_BLUE);
  printf("yellow on blue\n");
}
Enter fullscreen mode Exit fullscreen mode

Unlike Linux, where each foreground and background color has an individual number, you work with the red, green and blue channels on Windows. As you can see with yellow, it's a combination of red and green for example.

You can check available color values here.

Latest comments (2)

Collapse
 
craqqed_ profile image
Gavin Hayes

is there any way to change the color of the output when using a variable? something like:
string word = "break";
cout << word << endl;
but with colors

Collapse
 
juanitotelo profile image
Juan David Martinez Mercado • Edited

maybe
cout << "\033[c1;c2" << word << "\033[0" << endl;
where c1 is the background color number and c2 is foreground color number.
:)