loading...

CPP output coloured text in console

deebuls profile image Deebul Nair ・1 min read

Coloured Debug output

Print statements are the most widely used debug method for coding in any programming. Its always useful to have a bag of methods for good print statements for debugging.

One of the method is to color the output on the screen. Coloured debug statements are far more effective that plain white statements. For example can have green for positive statements and red for error statements.

In cpp there are tons of ways of doing things. I always like the KISS (keep it simple silly) method . The below code seems the most simplest way of doing it.

#include <iostream>
#include <string>


int main()
{
    const std::string red("\033[0;31m");
    const std::string green("\033[1;32m");
    const std::string yellow("\033[1;33m");
    const std::string cyan("\033[0;36m");
    const std::string magenta("\033[0;35m");
    const std::string reset("\033[0m");

    std::cout << yellow << " Hello color yellow " << reset << std::endl;
    std::cout << red << " Hello color red " << reset << std::endl;
    std::cout << green << " Hello color green " << reset << std::endl;
    std::cout << cyan <<" Hello color cyan " << reset << std::endl;
    std::cout << magenta << " Hello color magenta " << reset << std::endl;
     return 0;
}

Obviously it has its drawbacks. I don't know now , but feel free to comment ✏️ of it doesn't work for you .

Discussion

pic
Editor guide
Collapse
willkirkby profile image
Will Kirkby

Naturally, this doesn't work on Windows :)

Collapse
christianparpart profile image
Christian Parpart

You actually can use this on windows, but you've to tell conhost about that.

bool initializeConsoleVT()
{
    if (auto handle = GetStdHandle(STD_OUTPUT_HANDLE); handle)
    {
        DWORD mode = 0;
        if (GetConsoleMode(handle, &mode) != 0)
        {
            mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
            if (SetConsoleMode(handle, mode))
                return true;
        }
    }
    return false;
}
Collapse
deebuls profile image
Deebul Nair Author

Yes true !! Only works for linux. Not touched windows for years.

Collapse
pratikgaurav26 profile image
प्रतीक गौरव

hey, I tried this code in code blocks but it didn't work.
can you tell me why?