tags:

views:

85

answers:

6

How to add different colors in the C++ console ? , can use a one color but is there a way to use different colors in console ?

+4  A: 

Add a little Color to your Console Text

alt text

Sheen
Note that this is Windows-only.
DarkDust
Thanks but this doesn't help to use different colors in the same console window
Sudantha
@Sudantha, result snapshot attached.
Sheen
+4  A: 

Standard C++ has no notion of 'colors'. So what you are asking depends on the operating system.

For Windows, you can check out the SetConsoleTextAttribute function.

On *nix, you have to use the ANSI escape sequences.

sukhbir
+1  A: 

Here cplusplus example is an example how to use colors in console.

lmmilewski
+1  A: 

Assuming you're talking about a Windows console window, look up the console functions in the MSDN Library documentation.

Otherwise, or more generally, it depends on the console. Colors are not supported by the C++ library. But a library for console handling may/will support colors. E.g. google "ncurses colors".

For connected serial terminals and terminal emulators you can control things by outputting "escape sequences". These typically start with ASCII 27 (the escape character in ASCII). There is an ANSI standard and a lot of custom schemes.

Cheers & hth.,

Alf P. Steinbach
+2  A: 

I'm not sure what you really want to do, but my guess is you want your C++ program to output colored text in the console, right ? Don't know about Windows, but on all Unices (including Mac OS X), you'd simply use ANSI escape sequences for that.

DarkDust
A: 

You can write methods and call like this


HANDLE  hConsole;
    hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    int col=12;color

// color your text in Windows console mode
// colors are 0=black 1=blue 2=green and so on to 15=white  
// colorattribute = foreground + background * 16
// to get red text on yellow use 4 + 14*16 = 228
// light red on yellow would be 12 + 14*16 = 236

            FlushConsoleInputBuffer(hConsole);
    SetConsoleTextAttribute(hConsole, col);

             cout << "Color Text";

SetConsoleTextAttribute(hConsole, 15); //set back to black background and white text
Sudantha