Wizard Wizard - 2 months ago 34
C++ Question

How to change text or background color in a Windows console application

Which C++ function changes text or background color (MS Visual studio)? For example

cout<<"This text";
how to make "This text" red color.


Colour isn't a C++ thing, but a property of your terminal. If your terminal speaks ANSI (e.g. any Linux terminal, or DOS or Windows NT if you add DEVICE=C:\DOS\ansi.sys to your config.sys, or later Windows up till Windows 10 if you use the ansicon 3rd party program and e.g. call the shell with cmd.exe /kansicon, or in Windows 10 by default), then you can try the following gimmick:

#define ANSI_COLOR_RED     "\x1b[31m"
#define ANSI_COLOR_GREEN   "\x1b[32m"
#define ANSI_COLOR_YELLOW  "\x1b[33m"
#define ANSI_COLOR_BLUE    "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN    "\x1b[36m"

#define ANSI_COLOR_BRIGHT  "\x1b[1m"
#define ANSI_COLOR_RESET   "\x1b[0m"

std::cout << ANSI_COLOR_RED "Hello World\n" ANSI_COLOR_RESET;

Wikipedia has a list of ANSI escape sequences.