0

I'm trying to change the color of the text in c++, the only answer I can find is for C and not C++. I have tried using conio.h but don't understand how to use it. Could anyone help with this?

  • Does this answer your question? [How to change text and background color?](https://stackoverflow.com/questions/9965710/how-to-change-text-and-background-color) – emegona Aug 31 '20 at 04:04
  • C++ has no notion of "*text color*", so this is not possible in a portable way. For platform specific solutions see for example [Colorizing text in the console with C++](https://stackoverflow.com/questions/4053837/colorizing-text-in-the-console-with-c). – dxiv Aug 31 '20 at 04:12
  • You can't with conio.h, it's platform specific. But in some compiler like Borland, you can find `textColor()` but you can't admit that it's always here – thibsc Aug 31 '20 at 04:45
  • There is no `conio.h` defined in the C++ standard. Don't use non-portable non-standard headers (especially those from the DOS era `:)` – David C. Rankin Aug 31 '20 at 04:56
  • Does this answer your question? [Colorizing text in the console with C++](https://stackoverflow.com/questions/4053837/colorizing-text-in-the-console-with-c) – David C. Rankin Aug 31 '20 at 04:56

3 Answers3

1

Text coloring isn't really on the C++ side. In some unix terminals you could simply use codes like \e[0;31m message \e[0m directly in your program (although you might want to create an API for ease of use). However, this wouldn't work in a Windows console. It depends on the OS and terminal being used.

emegona
  • 168
  • 1
  • 12
1

If you don't need to stick to non cross-platform library conio.h. I recommend to use cross-platform solution: header only, moderc C++ rang library. I use it in most of my projects, it's really easy to use

0

I found out how to change the color of text using windows.h. Here is an example of the code I used (copied from https://cboard.cprogramming.com/).

#include <iostream>
#include <windows.h>

using namespace std;

int main()
{
    HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);                                  // h is your link to the console
    SetConsoleTextAttribute(h, 1);    cout << "Sentence in blue" << '\n';        // 1 happens to be blue
    SetConsoleTextAttribute(h, 2);    cout << "Sentence in green" << '\n';       // 2 is green
    SetConsoleTextAttribute(h, 4);    cout << "Sentence in red" << '\n';         // 4 is red
    SetConsoleTextAttribute(h, 7);    cout << "Sentence in white" << '\n';       // etc.
}