Colorizing text in the console with C++
How can I write colored text to the console with C++? That is, how can I write different text with different colors?
Solution 1:
Add a little Color to your Console Text
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
// you can loop k higher to see more color choices
for(int k = 1; k < 255; k++)
{
// pick the colorattribute k you want
SetConsoleTextAttribute(hConsole, k);
cout << k << " I want to be nice today!" << endl;
}
Character Attributes Here is how the "k" value be interpreted.
Solution 2:
ANSI escape color codes :
Name FG BG
Black 30 40
Red 31 41
Green 32 42
Yellow 33 43
Blue 34 44
Magenta 35 45
Cyan 36 46
White 37 47
Bright Black 90 100
Bright Red 91 101
Bright Green 92 102
Bright Yellow 93 103
Bright Blue 94 104
Bright Magenta 95 105
Bright Cyan 96 106
Bright White 97 107
Sample code for C/C++ :
#include <iostream>
#include <string>
int main(int argc, char ** argv){
printf("\n");
printf("\x1B[31mTexting\033[0m\t\t");
printf("\x1B[32mTexting\033[0m\t\t");
printf("\x1B[33mTexting\033[0m\t\t");
printf("\x1B[34mTexting\033[0m\t\t");
printf("\x1B[35mTexting\033[0m\n");
printf("\x1B[36mTexting\033[0m\t\t");
printf("\x1B[36mTexting\033[0m\t\t");
printf("\x1B[36mTexting\033[0m\t\t");
printf("\x1B[37mTexting\033[0m\t\t");
printf("\x1B[93mTexting\033[0m\n");
printf("\033[3;42;30mTexting\033[0m\t\t");
printf("\033[3;43;30mTexting\033[0m\t\t");
printf("\033[3;44;30mTexting\033[0m\t\t");
printf("\033[3;104;30mTexting\033[0m\t\t");
printf("\033[3;100;30mTexting\033[0m\n");
printf("\033[3;47;35mTexting\033[0m\t\t");
printf("\033[2;47;35mTexting\033[0m\t\t");
printf("\033[1;47;35mTexting\033[0m\t\t");
printf("\t\t");
printf("\n");
return 0;
}
GCC :
g++ cpp_interactive_terminal.cpp -o cpp_interactive_terminal.cgi
chmod +x cpp_interactive_terminal.cgi
./cpp_interactive_terminal.cgi