How to use the ANSI Escape code for outputting colored text on Console
A note to anybody reading this post: https://en.wikipedia.org/wiki/ANSI_escape_code#DOS_and_Windows
In 2016, Microsoft released the Windows 10 Version 1511 update which unexpectedly implemented support for ANSI escape sequences. The change was designed to complement the Windows Subsystem for Linux, adding to the Windows Console Host used by Command Prompt support for character escape codes used by terminal-based software for Unix-like systems. This is not the default behavior and must be enabled programmatically with the Win32 API via
SetConsoleMode(handle, ENABLE_VIRTUAL_TERMINAL_PROCESSING)
under windows 10 one can use VT100 style by activating the VT100 mode in the current console :
#include <windows.h>
#include <iostream>
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#define DISABLE_NEWLINE_AUTO_RETURN 0x0008
int main()
{
HANDLE handleOut = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD consoleMode;
GetConsoleMode( handleOut , &consoleMode);
consoleMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
consoleMode |= DISABLE_NEWLINE_AUTO_RETURN;
SetConsoleMode( handleOut , consoleMode );
for (int i = 0; i < 10; ++i)
{
std::cout << "\x1b[38;2;" << 5 * i << ";" << 255 - 10 * i << ";220m"
<< "ANSI Escape Sequence " << i << std::endl;
}
}
see msdn page : [https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences][1]
I'm afraid you forgot the ESC character:
#include <cstdio>
int main()
{
printf("%c[%dmHELLO!\n", 0x1B, 32);
}
Unfortunately it will only work on consoles that support ANSI escape sequences (like a linux console using bash, or old Windows consoles that used ansi.sys)
I created a very simple text-management library some time ago, being multiplatform, it uses native API calls for Windows and ANSI escape sequences for the rest of the platforms. It is fully documented and you can also browse the source code.
About your specific question, I think you are missing some codes. For example, in order to change the color of text, you should use something like:
static const char * CSI = "\33[";
printf( "%s%s", CSI, "31m" ); // RED
Hope this helps.