Colorization ANSI escape codes use Select Graphic Rendition (SGR) sequences, which are of the form CSI n m
, where a CSI
(which stands for Control Sequence Introducer) sequence is just the escape character followed by an opening square brace, n
is some parameter, and m
is the literal "m" character.
The tricky part is really just getting the escape character in a C++ string literal. You can see https://en.cppreference.com/w/cpp/language/escape for info about string escapes in C++. The TL;DR is that you can use octal form like \nnn
, or hexadecimal form like \xn...
. The ESC character in ASCII is value 27, which in octal is 33, and in hexadecimal, is 1b. So you can either use "\033[...m"
or "\x1b[...m"
.
For example:
"\033[31mred \033[33myellow \033[32mgreen \033[36mcyan \033[34mblue \033[35mmagenta"
"\x1b[31mred \x1b[33myellow \x1b[32mgreen \x1b[36mcyan \x1b[34mblue \x1b[35mmagenta"
(fun fact: Bash uses similar escape sequences for strings, so you can echo -e
the above string literals in a Bash shell and it will also work)
For C++20, I use the following snippet in a header file in one of my projects to define some more readable constants:
#include <string_view>
struct SgrPair final {
std::string_view on;
std::string_view off;
};
#if USE_ANSI_ESC
#define SGR(NAME, ON_STR, OFF_STR) inline constexpr SgrPair NAME { .on {(ON_STR)}, .off {(OFF_STR)} };
#else
#define SGR(NAME, ON_STR, OFF_STR) inline constexpr SgrPair NAME { .on {""}, .off {""} };
#endif
SGR(dim, "\033[2m", "\033[22m")
SGR(red, "\033[31m", "\033[39m")
#undef SGR
In the above snippet, the user doing the compilation can choose whether or not to define the USE_ANSI_ESC
macro to a truthy value.
See also List of ANSI color escape sequences and https://www.ecma-international.org/publications-and-standards/standards/ecma-48/.
Windows pain and suffering fun
If your program is printed to a Windows console like cmd, you need to write something in your program to enable ANSI escape codes in that console (see https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences):
#ifdef _WIN32
#include <windows.h>
#endif
int main() {
// ...
#ifdef _WIN32
DWORD con_mode;
GetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), &con_mode);
con_mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), con_mode);
// ...
}
The other answers already touched on this, but I added some preprocessor wrapping to make it easier to compile on non-Windows platforms without changing the code.
What "textcolor" is
It's a Turbo C/C++ Compiler function. See page 384 of the Turbo C/C++ Compiler 2.0 docs. See also: conio.h doesn't contain textcolor()?.