How to print colors in Xcode OS X
Hi all. I am learning C++ with tutorials online, but all of them seem to be on Windows. I got to the point where they were showing how to print in colours but apparently you need the command: #include <Windows.h>. OS X doesn't have that command. What is an alternative way I can print in color using 'cout'?
Thanks.
Re: How to print colors in Xcode OS X
Hi, AFAIK there's a nice and free library available for manipulating the console under *nix systems and it is called ncurses.
Re: How to print colors in Xcode OS X
firtsly, note that iostream ( and hence cout ) just deals with character based input output and knows knothing about how those character will be displayed or ultimately interpreted.
In order to control character appareance you'll need a terminal API, like windows console functions or a full fledged terminal ui library like ncurses suggested by AvDav.
That said, most unix terminals support ansi escape sequences, that include simple color support, so no library is needed to use them:
Code:
#include <iostream>
#define ANSI_RED "\x1b[31m"
#define ANSI_GREEN "\x1b[32m"
#define ANSI_YELLOW "\x1b[33m"
#define ANSI_BLUE "\x1b[34m"
#define ANSI_MAGENTA "\x1b[35m"
#define ANSI_CYAN "\x1b[36m"
#define ANSI_BLACK "\x1b[0m"
int main()
{
std::cout << ANSI_BLUE "this is blue" ANSI_BLUE << std::endl
<< ANSI_RED "this is red" ANSI_RED << std::endl
<< ANSI_BLACK "this is black" ANSI_BLACK << std::endl;
// remember to reset color before exit ...
}
clearly, the above is not portable and you should not use it for anything serious ... ( unless you're targeting a specific terminal emulator )
Re: How to print colors in Xcode OS X
Most *nix consoles provide some form of terminal emulation - usually default to VT100 AFAIK- so most VT100 escape codes work. See http://www.termsys.demon.co.uk/vtansi.htm for further escape code details.