23

I was wondering how can I print colorful text in the console? I use eclipse win64 OS. Does it have to do with the compiler? Can anyone give a simple example in C with just a hello world text in red or whatever?

oguz ismail
  • 1
  • 16
  • 47
  • 69
BugShotGG
  • 5,008
  • 8
  • 47
  • 63
  • 5
    C doesn't define color output; it depends on the features of the terminal you're using. Probably there are some escape sequences you can print to get color output. You'll have to find out what those escape sequences are, and then just print them. (An ASCII escape character can be represented as `"\x1B"`.) – Keith Thompson Jan 06 '12 at 23:45
  • 1
    If you can, I suggest using C++. It will make life in this way a lot easier. I am guessing you are doing it for learning, so good for you. – nmagerko Jan 06 '12 at 23:48
  • @nmagerko Could you plz tell me how to color the backround of the console? thanks :) – BugShotGG Jan 07 '12 at 00:56
  • Unfortunately, I do not know how to do this is C. C++ would make this MUCH easier, not to mention that fact that the program you create would be much easier to port to other platforms. – nmagerko Jan 07 '12 at 02:36
  • For *nix: [check this out](http://linuxgazette.net/issue65/padala.html) For windoze: [here](http://www.dreamincode.net/forums/topic/17822-print-certain-text-in-color/) – Dhaivat Pandya Jan 06 '12 at 23:45

6 Answers6

25

I know that this is incredibly easy to do in C++, but I found this for you to look at in C:

#include <stdio.h>
#include <windows.h>   // WinApi header

int main()
{
  HANDLE  hConsole;
    int k;

  hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

  // you can loop k higher to see more color choices
  for(k = 1; k < 255; k++)
  {
    SetConsoleTextAttribute(hConsole, k);
    printf("%3d  %s\n", k, "I want to be nice today!");
  }

  getchar();  // wait
  return 0;
}

All of the comments will help you to find your way through the code - hope it helps!

nmagerko
  • 6,586
  • 12
  • 46
  • 71
  • 1
    Aww... well, I thought to achieve this by using ANSI. I'd have to write myself a function to parse the strins and change the attributes I suppose... – Tomáš Zato May 09 '14 at 22:10
  • @TomášZato, ANSI won’t work in Windows anymore because the device driver is 16-bit and thus not compatible with 64-bit systems (nor even included anymore). – Synetech Apr 01 '16 at 05:03
  • 4
    What do you mean by 'I know that this is incredibly easy to do in C++'? – Arwed Mett Aug 21 '17 at 11:52
  • If you drop the printf and getchar() statments, you could make a color function. The "k" will be an int you pass in. If you go that route than this is a perfect case to use an enum to make your own type. – Travis Mar 26 '18 at 08:14
7

You can use ANSI escape sequence on Windows as well with the following modification:

reg add HKEY_CURRENT_USER\Console /v VirtualTerminalLevel /t REG_DWORD /d 0x00000001 /f

example:

int main() 
{
   printf("\033[33mThis is yellow\033[0m");
   return 0;
}

source: https://www.codeproject.com/Tips/5255355/How-to-Put-Color-on-Windows-Console

dajuric
  • 2,373
  • 2
  • 20
  • 43
7

If you want to print colored text in Windows console, you will have to use Windows API. ANSI.sys support is no longer present in Windows.

In Linux you can still use ANSI escape sequences to color text.

Šimon Tóth
  • 35,456
  • 20
  • 106
  • 151
  • escape seq table here: http://ascii-table.com/ansi-escape-sequences.php Example: printf("\x1b[1m Enable_BOLD \n \x1b[0m"); – Doug Oct 30 '14 at 19:50
3

If you are constrained to using just printf(), this requires knowledge of the terminal to which you're writing. The chances are it is an ANSI-style terminal, so it can be done. The Unix curses (Linux ncurses) library handles such information in a terminal-independent way. Basically, you will need to define or manufacture control strings to turn the terminal into red mode and then reset it back again (but how do you know what state it was in before you changed it to writing red text?). The libraries mentioned keep track of the state information, amongst many other details.

However, if you get the strings organized, then code like this will do the trick (more or less):

static const char to_red[] = "\033...";
static const char to_black[] = "\033...";

printf("%s%s%s\n", to_red, "hello world", to_black);

The hard part is determining what goes in the constant strings (which need not actually be constant).

All this means there is probably a Windows-specific interface that can be used to do the job, but that does not really involve printf() for controlling the colours; you call the Windows API to set the colour, then write with printf(), then call the API again to reinstate the colour. There is probably a query function to allow you to find the current setting, which you use before changing it.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
0

Here's a further example for you. It is in C++, but I'm sure you can handle that; but I do also have the exact same code in this example in python. It's a small demo I wrote to end up drawing some lines in colors.

enter image description here

Anyway the series of demos is at:

https://github.com/goblinhack/c-plus-plus-python-tutorial

With the full source for the below example at:

https://github.com/goblinhack/c-plus-plus-python-tutorial/blob/master/lesson1/lesson1.cpp

The C++ code for the above picture is using the Ansi color class I define in the lesson1.cpp. But once you use that, it's very simple to use. hth.

int main (int argc, char *argv[])
{
    Ansi ansi;

    std::cout << ansi.get_code(ansi.FOREGROUND_RED);
    std::cout << "hello ";

    std::cout << ansi.get_code(ansi.FOREGROUND_GREEN);
    std::cout << "beautiful";
    std::cout << ansi.get_code(ansi.RESET);

    std::cout << ansi.get_code(ansi.FOREGROUND_CYAN);
    std::cout << " colorful";
    std::cout << ansi.get_code(ansi.RESET);

    std::cout << ansi.get_code(ansi.FOREGROUND_BLUE);
    std::cout << " world";
    std::cout << ansi.get_code(ansi.RESET);
    std::cout << std::endl;

    return (0);
}

With similar ability in python

 def lesson1():
        """ hello beautiful world """
        ansi = Ansi()

        for bg_col in range(ansi.Code.BACKGROUND_BLACK,
                            ansi.Code.BACKGROUND_WHITE):
            for fg_col in range(ansi.Code.FOREGROUND_BLACK,
                                ansi.Code.FOREGROUND_WHITE):
                sys.stdout.write("{0: <20} {1: <20}".format(\
                                 ansi.get_code_name(bg_col),
                                 ansi.get_code_name(fg_col)))
                sys.stdout.write(ansi.get_bgfg_code(bg_col, fg_col))
                sys.stdout.write("colorful")
                sys.stdout.write(ansi.get_code(ansi.Code.RESET))
                print()

        sys.stdout.write(ansi.get_code(ansi.Code.FOREGROUND_RED))
        sys.stdout.write("hello")

        sys.stdout.write(ansi.get_code(ansi.Code.FOREGROUND_GREEN))
        sys.stdout.write(" beautiful")

        sys.stdout.write(ansi.get_code(ansi.Code.FOREGROUND_CYAN))
        sys.stdout.write(" colorful")

        sys.stdout.write(ansi.get_code(ansi.Code.FOREGROUND_BLUE))
        sys.stdout.write(" world")

        sys.stdout.write(ansi.get_code(ansi.Code.RESET))
        print("from Python")

    lesson1()
Goblinhack
  • 2,859
  • 1
  • 26
  • 26
0

The console in Java uses stdout which is whatever OS you are running on. For Windows, you would need to access the Console API to change the colours. For Linux or Mac, the console might support ANSI escape sequences which can change the console colours via stdout.

CodeSlinger
  • 429
  • 3
  • 8