How can I write colored text to the console with C++? That is, how can I write different text with different colors?
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.
I'm not sure what you really want to do, but my guess is you want your C++ program to output colored text in the console, right ? Don't know about Windows, but on all Unices (including Mac OS X), you'd simply use ANSI escape sequences for that.
Assuming you're talking about a Windows console window, look up the console functions in the MSDN Library documentation.
Otherwise, or more generally, it depends on the console. Colors are not supported by the C++ library. But a library for console handling may/will support colors. E.g. google "ncurses colors".
For connected serial terminals and terminal emulators you can control things by outputting "escape sequences". These typically start with ASCII 27 (the escape character in ASCII). There is an ANSI standard and a lot of custom schemes.
On Windows 10 you may use escape sequences this way:
#ifdef _WIN32
SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), ENABLE_VIRTUAL_TERMINAL_PROCESSING);
#endif
// print in red and restore colors default
std::cout << "\033[32m" << "Error!" << "\033[0m" << std::endl;
Standard C++ has no notion of 'colors'. So what you are asking depends on the operating system.
For Windows, you can check out the SetConsoleTextAttribute function.
On *nix, you have to use the ANSI escape sequences.
The simplest way you can do is:
#include <stdlib.h>
system("Color F3");
Where "F" is the code for the background color and 3 is the code for the text color.
Mess around with it to see other color combinations:
system("Color 1A");
std::cout << "Hello, what is your name?" << std::endl;
system("Color 3B");
std::cout << "Hello, what is your name?" << std::endl;
system("Color 4c");
std::cout << "Hello, what is your name?" << std::endl;
Note: I only tested on Windows. Works. As pointed out, this is not cross-platform, it will not work on Linux systems.