Color text output in Console in C++

In general, when we execute any program in C++ we observe that the output text is in white color on black background. But in C++, we can change the color of the text on the console and we can also change the background color on the output screen. In this article, we will discuss how we can print colored text on the output screen with a simple example program.

Colorizing text on the output screen in C++ :

In C++, we use the following syntax for coloring the text on the output console.

Handle var_name = GetStdHandle(STD_OUTPUT_HANDLE);

SetConsoleTextAttribute(var_name, color_code);

We have to include any one of the header files to color the text on the output console.

#include <windows.h>  or #include <stdlib.h>

Color codes are numbers. We have 255 color codes, in those 1-15 color codes are used for text coloring, and numbers after 15 are used for background coloring of the console screen. Below is the program to do so.

Code : 

#include <iostream>
#include <windows.h>
using namespace std;
1  : Blue
2  : Green
3  : Cyan
4  : Red
5  : Purple
6  : Yellow(dark)
7  : Default white
8  : Grey
9  : Bright blue
10 : Bright green
11 : Bright cyan
12 : Bright red
13 : pink
14 : yellow
15 : Bright white

int main()

    HANDLE col;
    col =  GetStdHandle(STD_OUTPUT_HANDLE);
    for (int col_code = 1; col_code < 16; col_code++) {
        SetConsoleTextAttribute(col, col_code);
        cout << col_code << "Welcome to CodeSpeedy!\n ";
    return 0;

Output :

color text output in console c++

In the above code initially, we included a windows header file to use some of its methods and we are using namespace std for console output. Here we iterate a loop from 0-15 to get colored text output on the console. If we repeat the loop for variable col_code until 255 then we will get a different background color on the console output from the 16th line onwards.

The output text we are printing is “Welcome to CodeSpeedy!” get printed in 15 different colors.

Leave a Reply

Your email address will not be published. Required fields are marked *