How to Change Console Color in C++?
In C++, most of the inbuilt input and output functions take input and show output from/to the console window. This can be useful for highlighting important information, creating visually appealing interfaces, or simply adding a touch of personalization to our console applications.
How to Change Console Color in C++?
By default, the console color is generally black text and white background but we can customize the appearance of our console output by changing the text and background colors using ANSI color codes.
ANSI escape codes are special character sequences that can be embedded within text to control formatting, including colors. While it is not supported on all platforms, ANSI escape codes offer some degree of portability.
Code | Color | Code | Color |
---|---|---|---|
30 | Black | 90 | Bright Black |
31 | Red | 91 | Bright Red |
32 | Green | 92 | Bright Green |
33 | Yellow | 93 | Bright Yellow |
34 | Blue | 94 | Bright Blue |
35 | Magenta | 95 | Bright Magenta |
36 | Cyan | 96 | Bright Cyan |
37 | White | 97 | Bright White |
Syntax of ANSI Color Codes
To use these codes in C++, you can use the \033 ANSI escape sequence followed by the code and m.
cout << "\033[32mThis is red text";
This change will be applied to all the text after this text. To reset is use [0m code.
C++ Program For Changing Console Color
#include <iostream>
using namespace std;
// Function to set the console text color using ANSI escape
// codes
void SetColor(int textColor)
{
cout << "\033[" << textColor << "m";
}
// Function to reset the console color
void ResetColor() { cout << "\033[0m"; }
int main()
{
// Set text color to bright white (97) and background
// color to blue (44)
SetColor(31);
cout
<< "This text is bright white on a blue background."
<< endl;
// Reset to default colors
ResetColor();
cout << "This text is the default color." << endl;
return 0;
}
Output

Using Windows.h Functions (Windows-specific)
This approach provides direct access to console color manipulation functions on Windows systems. It offers a wider range of color options and customization possibilities.
Steps:
- Include the <Windows.h> header
- Get a handle to the console window.
- Use SetConsoleTextAttribute function to change the console colors.
C++ Program to change console colors using Windows API:
#include <iostream>
#include <windows.h>
using namespace std;
// Function to set the console text and background color
void SetColor(int textColor, int bgColor)
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole,
(bgColor << 4) | textColor);
}
int main()
{
// Set text color to white and background color to blue
SetColor(15, 1);
cout << "This text is white on a blue background."
<< endl;
// Reset to default colors
SetColor(7, 0);
cout << "This text is the default color." << endl;
return 0;
}
Output