1

I change the background and text color in my console by using the "system" command.

    #include <iostream>

using namespace std;

int main()
{
system ("color 1a");
cout <<"Hello World";

cin.ignore();
return 0;
}

Is there a way to change color in only one line? C or C++ are fine. Thanks.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
user2948288
  • 36
  • 1
  • 1
  • 4
  • 2
    There is certainly a better way than the system command, but it will be platform dependent and you didn't mention the platform you're using. – Retired Ninja Dec 22 '13 at 02:53

1 Answers1

7

I assume you are using Windows, as your system() function is executing color which is a console utility for Windows.

If you are going to write your program for Windows and you want to change color of text and/or background, use this:

   SetConsoleTextAttribute (GetStdHandle(STD_OUTPUT_HANDLE), attr);

Where attr is a combination of values with | (bitwise OR operator), to choose whther you want to change foreground or background color. Changes apply with the next function that writes to the console (printf() for example).

Details about how to encode the attr argument, here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682088%28v=vs.85%29.aspx#_win32_character_attributes

For example, this programs prints "Hello world" using yellow text (red+green+intensity) over blue background, in a computer with Windows 2000 or later:

#include <stdio.h>
#include <windows.h>

int main()
{
  SetConsoleTextAttribute (GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED |
                                                            FOREGROUND_GREEN | 
                                                            FOREGROUND_INTENSITY | 
                                                            BACKGROUND_BLUE
                          );
  printf ("Hello world\n");
  return 0;
}

This other shows a color chart showing all combinations for foreground and background colors:

#include <stdio.h>
#include <windows.h>

int main()
{
  unsigned char b,f;

  for (b=0;b<16;b++)
  {
    for (f=0;f<16;f++)
    {
        SetConsoleTextAttribute (GetStdHandle(STD_OUTPUT_HANDLE), b<<4 | f);
        printf ("%.2X", b<<4 | f);
    }
    printf ("\n");
  }
  SetConsoleTextAttribute (GetStdHandle(STD_OUTPUT_HANDLE), 0x07);
  printf ("\n");
  return 0;
}
mcleod_ideafix
  • 11,128
  • 2
  • 24
  • 32