tony
tony

Reputation: 181

Colors in C++ win32 console

std::cout << "blblabla... [done]" << std::endl;

Is it possible to make [done] be in another color, and possibly bold? I'm using Windows 7

Upvotes: 18

Views: 17569

Answers (5)

Kuzgun
Kuzgun

Reputation: 4737

A quick way: include #include <stdlib.h> and then add system( "color 5B" ); before the text you want. So it will look like this:

#include <stdlib.h>
std::cout << "blblabla..."<<std::endl;
system( "color 5B" );
std::cout<< "[done]" << std::endl;

You can try different colors: 1A, 2B, 3C, 4F...

Upvotes: -5

Dirk is no longer here
Dirk is no longer here

Reputation: 368201

Yes, you just send a standard escape sequence, e.g.

    const char* green = "\033[0;32m";
    const char* white = "\033[0;37m";
    const char* red   = "\033[0;31m";
    double profit = round(someComplicatedThing());
    std::cout << (profit < 0 ? red : (profit > 0 ? green : white))
              << "Profit is " << profit << white << std::endl;

You also get bold vs normal, colored background etc. The Wikipedia page on ANSI escape code has details, the Bash-Prompt HOWTO has examples.

Upvotes: 7

Khaled Alshaya
Khaled Alshaya

Reputation: 96859

You can use this tiny libraries which I have used personally before. It is very easy to use and integrate with standard streams. It has a clear console screen functionality btw. This example is from a code I wrote:

    std::cout << con::clr; // Clear the Intro Screen
// fg means the foreground
std::cout << std::endl << std::endl << con::fg_green
    << "\t\tFile Encrypted!";

Upvotes: 4

H4cKL0rD
H4cKL0rD

Reputation: 5508

Yes you can you can use the system(); function to run commands from the command.com and one of those is color. color a will get you the green you want. you may also see other colors from the help option color /? . and for the bold thing you can use characters from ascii chart to do that. such as "\n" Is Newline.

Upvotes: -1

Brian R. Bondy
Brian R. Bondy

Reputation: 347216

This depends on which OS you are using.

If you're using windows you want SetConsoleTextAttribute:

HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);  // Get handle to standard output
SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE);

You can also combine values.

An application can combine the foreground and background constants to achieve different colors. For example, the following combination results in bright cyan text on a blue background.

FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_BLUE

You can then use WriteFile or WriteConsole to actually write the the console.

Upvotes: 21

Related Questions