# C++ console text color.



## Codiah (Sep 27, 2008)

Hey its been a while since I've come to tech guy for a helping hand, but its the best source of information and after a good few days of searching Google over i haven't found a very definitive answer to my question. Below is an example of what i've been doing to create colored text in my console programs. however i have come to a problematic point in coding.

Before i get to in depth here, i am wanting to use colored text in a console program for a very specific reason, mainly to make an aesthetically pleasing hack and slash game I've been working on as a nostalgia project.

but the problem i'm facing is changing both the font and background colors for a string of text... if i use the values below that start with a 3 such as 32, 33, 34 and so on i can change text color. and i know that if i change that first three to a 4 such as 42, 43, 44 and so on i can change the background to the corresponding color. but how do i change both text and background colors for a string say as to get a dark red background with yellow text or something... is there a way to do this, is the way I'm currently doing this wrong or inefficient?

any help would be greatly appreciated. and I'm open to new ideas...

as a disclaimer, bear in mind i am extremely new to c/c++ , i learn by doing and experimenting, so if you could keep in mind your talking to someone with limited c/c++ knowledge.. thanks..


```
#include <iostream>

using namespace std;

int main()
{
    std::cout << "\033[0;" << 32 << "mHello!\033[0m" << std::endl;
    std::cout << "\033[0;" << 33 << "mHello World!\033[0m" << std::endl;
    std::cout << "\033[0;" << 34 << "mHello World Hello!\033[0m" << std::endl;
    std::cout << "\033[0;" << 35 << "mHello World Hello World!\033[0m" << std::endl;
    return 0;
}
```


----------



## Codiah (Sep 27, 2008)

BUMP - Any thoughts would be appreciated.


----------



## mt2002 (Sep 14, 2005)

Not in standard C. The Win32 API has a SetConsoleTextAttribute method that can be used to set the current text attributes to a console window:


```
#include <windows.h>

int main()
{
   HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
 
   // change color
   SetConsoleTextAttribute(hConsole, color);
}
```
The *color* is a value that represents *foreground + background * 16*, where foreground and background can be one of the standard 16 colors in console mode.


----------

