0

I would like to make colored text in console for each char (text). I tried to use
system("COLOR <COLOR_CODE>");
but it takes effect for all text. Can I color only some text?

Thank you very much for help :)

tomf42
  • 9
  • 1
  • Possible duplicate of [Color text in terminal applications in UNIX](http://stackoverflow.com/questions/3585846/color-text-in-terminal-applications-in-unix) – Nicholas Flees Feb 20 '17 at 19:32

3 Answers3

1

In the Window console, to color text you need to call SetConsoleTextAttribute. For example,

HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN | FOREGROUND_BLUE);

Make sure to include <windows.h>.

0

I wrote a cool header a while back:

#include <Windows.h>
enum colors {
    black = 0,
    electric = 1,
    leaf = 2,
    lightblue = 3,
    red = 4,
    darkpurple = 5,
    gold = 6,
    lightgrey = 7,
    grey = 8,
    blue = 9,
    green = 10,
    aqua = 11,
    lightred = 12,
    purple = 13,
    yellow = 14,
    white = 15,
};
namespace color {
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

    void print(std::string text, const int font = colors::lightgrey, const int background = colors::black) {
        bool inv = false;
        if (text[text.length() - 1] == '\n') {
            text.pop_back();
            inv = true;
        }
        int color;
        color = background * 16 + font;
        SetConsoleTextAttribute(hConsole, color);
        printf(text.c_str());
        SetConsoleTextAttribute(hConsole, 7);
        if (inv)
            printf("\n");
    }

    void printM(std::string text, const int color) {
        bool inv = false;
        if (text[text.length() - 1] == '\n') {
            text.pop_back();
            inv = true;
        }
        SetConsoleTextAttribute(hConsole, color);
        printf(text.c_str());
        SetConsoleTextAttribute(hConsole, 7);
        if (inv)
            printf("\n");
    }

    void map(const char* e = NULL)
    {
        for (size_t i = 0; i < 256; i++)
        {
            printM(std::to_string(i), i);
            printf(e);
        }
    }
};

The only downside is that if you're doing multithreading some stuff will get colored with other.

A18
  • 1
-1

Put #define color(param) printf("\033[%sm", param) #define green "32" #define white "0"

at the beginning of your file.

Then, use color(green) before your printf. 32 is for green, feel free to try other numbers to find what you like.

Dot31
  • 11
  • 2