Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

colorful text using printf in C

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?

like image 393
BugShotGG Avatar asked Jan 06 '12 23:01

BugShotGG


People also ask

How many colors are there in C language?

Total number of colors available are 16. Number of available colors depends on current graphics mode and driver. For example, setcolor(RED) or setcolor(4) changes the current drawing color to RED. Remember that default drawing color is WHITE.

How do you change colors in C++?

If You want to change the Text color in C++ language There are many ways. In the console, you can change the properties of output. click this icon of the console and go to properties and change color. The second way is calling the system colors.


2 Answers

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!

like image 50
nmagerko Avatar answered Oct 05 '22 01:10

nmagerko


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.

like image 33
Šimon Tóth Avatar answered Oct 05 '22 01:10

Šimon Tóth