385

How do I print coloured characters to a Linux terminal that supports it?

How do I tell whether the terminal supports colour codes?

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
Macha
  • 14,366
  • 14
  • 57
  • 69
  • 9
    To determine what the terminal is capable of, check the terminal capabilities database. see `termcap(5)`. – jrockway Apr 11 '10 at 12:10
  • 8
    "The termcap database is an obsolete facility for describing the capabilities of character-cell terminals and printers. It is retained only for capability with old programs; new ones should use the `terminfo(5)` database and associated libraries." -- `termcap(5)` – OrangeDog Apr 15 '14 at 15:23
  • You can easily you [termcolor](http://termcolor.readthedocs.org/en/latest/) – Rudy Jessop Feb 05 '16 at 06:20
  • 1
    Feel free to have a look at a code snippet I put [here](http://stackoverflow.com/questions/138383/colored-grep/138528#138528). It's a small tool that colors its output with the help of some macros. – epatel Apr 11 '10 at 12:26
  • 1
    If you want to do some advanced stuff with color printing, I suggest you read [this](http://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html) article. I found it very helpful – SubMachine Jun 20 '19 at 09:02

16 Answers16

552

You need to output ANSI colour codes. Note that not all terminals support this; if colour sequences are not supported, garbage will show up.

Example:

 cout << "\033[1;31mbold red text\033[0m\n";

Here, \033 is the ESC character, ASCII 27. It is followed by [, then zero or more numbers separated by ;, and finally the letter m. The numbers describe the colour and format to switch to from that point onwards.

The codes for foreground and background colours are:

         foreground background
black        30         40
red          31         41
green        32         42
yellow       33         43
blue         34         44
magenta      35         45
cyan         36         46
white        37         47

Additionally, you can use these:

reset             0  (everything back to normal)
bold/bright       1  (often a brighter shade of the same colour)
underline         4
inverse           7  (swap foreground and background colours)
bold/bright off  21
underline off    24
inverse off      27

See the table on Wikipedia for other, less widely supported codes.


To determine whether your terminal supports colour sequences, read the value of the TERM environment variable. It should specify the particular terminal type used (e.g. vt100, gnome-terminal, xterm, screen, ...). Then look that up in the terminfo database; check the colors capability.

Dinei
  • 4,494
  • 4
  • 36
  • 60
Thomas
  • 174,939
  • 50
  • 355
  • 478
  • 26
    This was the bee's knees on the BBS… – Potatoswatter Apr 11 '10 at 13:03
  • 13
    What does `m` do/stand for? – nipponese May 03 '14 at 20:51
  • Looking at the [table](http://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes) it seems pretty arbitrary. – Thomas May 04 '14 at 06:41
  • 1
    this ANSI's called "SGR code" or "Set graphics rendition" that [m]ods the attribute. Most terms do support the lower 8 colors ok, but you WILL get problems with how the upper ones are done. Of course it wont hurt anything but it is best not to be a habit, even worse, it should never be a suggestion that will be spread. Case in point, this "top" answer. See the next answer for the better idea (am unbiased here), you should avoid checking the terminfo, there are many libraries/binaries out there to do that for you. – osirisgothra Aug 22 '14 at 23:44
  • 4
    @nipponese `\033[` and `m` mark the beginning and end of the escape sequence for ANSI color codes. Ref: http://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes – thameera Sep 22 '14 at 08:27
  • 31
    I use it defining "manipulators", such as `const std::string red("\033[0;31m");` or `const std::string reset("\033[0m");`. Then, I can write simply `cout << red << "red text" << reset << endl;`. – Daniel Langr Feb 01 '16 at 08:26
  • 4
    I'd look at this for a visualization of the colors: http://misc.flogisoft.com/bash/tip_colors_and_formatting – Liran Funaro May 08 '17 at 10:17
  • Obviously, this also works for other languages, e.g. Java! Thanks! – Remigius Stalder Jun 13 '17 at 17:19
122

Basics

I have written a C++ class which can be used to set the foreground and background color of output. This sample program serves as an example of printing This ->word<- is red. and formatting it so that the foreground color of word is red.

#include "colormod.h" // namespace Color
#include <iostream>
using namespace std;
int main() {
    Color::Modifier red(Color::FG_RED);
    Color::Modifier def(Color::FG_DEFAULT);
    cout << "This ->" << red << "word" << def << "<- is red." << endl;
}

Source

#include <ostream>
namespace Color {
    enum Code {
        FG_RED      = 31,
        FG_GREEN    = 32,
        FG_BLUE     = 34,
        FG_DEFAULT  = 39,
        BG_RED      = 41,
        BG_GREEN    = 42,
        BG_BLUE     = 44,
        BG_DEFAULT  = 49
    };
    class Modifier {
        Code code;
    public:
        Modifier(Code pCode) : code(pCode) {}
        friend std::ostream&
        operator<<(std::ostream& os, const Modifier& mod) {
            return os << "\033[" << mod.code << "m";
        }
    };
}

Advanced

You may want to add additional features to the class. It is, for example, possible to add the color magenta and even styles like boldface. To do this, just an another entry to the Code enumeration. This is a good reference.

Joel Sjögren
  • 2,010
  • 1
  • 13
  • 12
  • Great‌‌‌‌‌‌‌‌‌‌‌. It can be helpful if you can add other colors and also background colors. – Minimus Heximus Aug 03 '13 at 14:19
  • 8
    some more: ` FG_DEFAULT = 39, FG_BLACK = 30, FG_RED = 31, FG_GREEN = 32, FG_YELLOW = 33, FG_BLUE = 34, FG_MAGENTA = 35, FG_CYAN = 36, FG_LIGHT_GRAY = 37, FG_DARK_GRAY = 90, FG_LIGHT_RED = 91, FG_LIGHT_GREEN = 92, FG_LIGHT_YELLOW = 93, FG_LIGHT_BLUE = 94, FG_LIGHT_MAGENTA = 95, FG_LIGHT_CYAN = 96, FG_WHITE = 97, BG_RED = 41, BG_GREEN = 42, BG_BLUE = 44, BG_DEFAULT = 49` – Phantrast Apr 21 '14 at 11:23
  • 6
    If you define `operator<<` for `Code`, then you can directly write `std::cout << Color::FG_RED;` instead of `std::cout << Modifier(Color::FG_RED);`. That is, `Modifier` wouldn't be needed. – Nawaz May 21 '14 at 13:24
  • 2
    @Nawaz Good idea. Here's an implementation like that: http://pastebin.com/zWC3t9hC. However I'll keep my original implementation in the answer because I feel that it's more extensible. – Joel Sjögren May 26 '14 at 16:49
  • I have now changed my mind. Anything that you can do with my old implementation, you should be able to do with the new one as suggested by Nawaz by composition. – Joel Sjögren Jun 16 '14 at 08:44
  • 1
    Actually I like the first implementation better as you can add a flag to turn colors on or off: Add `bool sh;` to the class and change the constructor to `Modifier (Code pCode, bool show = true) : code(pCode), sh(show) {}`. Finally, in the body of the `<<` operator return the current line `if (sh)` and `return << os;` otherwise. This allows to write your code with `Color::Modifier red(Color::FG_RED, BoolVar);` where you can set `BoolVar` as true or false as a initialization of the program. You can turn it on to see it on the screen and off to redirect to a file. – rpsml Feb 06 '15 at 17:09
  • You can replace `std::ostream` with `std::wostream` to make it work with `std::wstring`s – Yılmaz Alpaslan Mar 18 '22 at 12:19
47

Before you going to output any color you need make sure you are in a terminal:

[ -t 1 ] && echo 'Yes I am in a terminal'  # isatty(3) call in C

Then you need to check terminal capability if it support color

on systems with terminfo (Linux based) you can obtain quantity of supported colors as

Number_Of_colors_Supported=$(tput colors)

on systems with termcap (BSD based) you can obtain quantity of supported colors as

Number_Of_colors_Supported=$(tput Co)

Then make you decision:

[ ${Number_Of_colors_Supported} -ge 8 ] && {
    echo 'You are fine and can print colors'
} || {
    echo 'Terminal does not support color'
}

BTW, do not use coloring as it was suggested before with ESC characters. Use standard call to terminal capability that will assign you CORRECT colors that particular terminal support.

BSD Based
fg_black="$(tput AF 0)"
fg_red="$(tput AF 1)"
fg_green="$(tput AF 2)"
fg_yellow="$(tput AF 3)"
fg_blue="$(tput AF 4)"
fg_magenta="$(tput AF 5)"
fg_cyan="$(tput AF 6)"
fg_white="$(tput AF 7)"
reset="$(tput me)"
Linux Based
fg_black="$(tput setaf 0)"
fg_red="$(tput setaf 1)"
fg_green="$(tput setaf 2)"
fg_yellow="$(tput setaf 3)"
fg_blue="$(tput setaf 4)"
fg_magenta="$(tput setaf 5)"
fg_cyan="$(tput setaf 6)"
fg_white="$(tput setaf 7)"
reset="$(tput sgr0)"
Use As
echo -e "${fg_red}  Red  ${fg_green} Bull ${reset}"
Cristian Ciupitu
  • 20,270
  • 7
  • 50
  • 76
Alex
  • 785
  • 6
  • 9
  • 4
    Isn't this bash specific? -t 1 obviously won't work in C++, and calling this tput program will make it very roundabout when in a C++ program. – Macha Oct 06 '12 at 22:00
  • 2
    @Macha, yes, `[ -t 1 ]` it's sh/bash specific, but on the right side after `#(comment)` sign there is C function that do the same. `man 3 isatty` should help on this ;) Example shown as shell commands to simplify explanation of main point. As about `tput` it's OPEN source utility to query standard terminal capability interface. – Alex Oct 12 '12 at 05:06
  • 1
    Im not sure why people keep suggesting to use those codes directly. It is really, really bad practice to make such assumptions. Even if this is shell specific code, it can be translated by anyone with even a novice amount of shell experience. – osirisgothra Aug 22 '14 at 23:45
  • `tput` is damn _slow_ working with C++, e.g. in an REPL implementation (each can take 0.06s, while typically a C++ process with dynamic system libraries has a total overhead of 0.02s in the startup and termination). And it is still not _that_ portable: ANSI escape code but not `tput` would just work fine with some new versions of Windows 10 or ConEmu with hook enabled. Even `tput` is available, it still needs to care about differences over `terminfo` v. `termcap`. – FrankHB Jun 09 '21 at 03:37
  • In fact, I just come here to find the improvement of [my implementation in C++](https://github.com/FrankHB/YSLib/blob/master/YFramework/source/YCLib/Host.cpp#L335). Seems nobody has already inline the `tput` calls in C/C++ by hand... – FrankHB Jun 09 '21 at 03:46
  • @FrankHB One need to call `tput` only once, on program start and remember needed escape color codes in some variables and use it while program works. So, IMHO `tput` slowness might be ignored in such case, especially if you take in account that "color" program dealing with humans, who are much slower than any computer. Using `tput` will guarantee that assumed/wanted colors are supported on particular system making it portable across platforms. – Alex Jun 09 '21 at 10:24
  • @Alex True, this does the work (and not that bad for a REPL used interactively); but it is still problematic in a batch-mode interpreter which may frequently evaluate some tiny scripts. Perhaps turning off the color output by default is a more correct way, but I still wonder some solutions capable for the cases where the scripts need this functionality (for output only). – FrankHB Jun 09 '21 at 17:49
  • Anyway, `tput` is already an external dependency, even worse than `` in C/C++. And taking the potential potability issue into account, I have the dilemma exactly like [this](https://github.com/Stebalien/term/issues/44), except that currently I don't need full-featured terminals and on Windows I just use native Win32 console API instead (it won't work with `mintty` without PTY, though). Perhaps I'll finally implement an ANSI fallback like this, as I can't re-implement a saner replacement of terminfo/termcap and maintain all the term conf files by myself... – FrankHB Jun 09 '21 at 18:00
45

As others have stated, you can use escape characters. You can use my header in order to make it easier:

#ifndef _COLORS_
#define _COLORS_

/* FOREGROUND */
#define RST  "\x1B[0m"
#define KRED  "\x1B[31m"
#define KGRN  "\x1B[32m"
#define KYEL  "\x1B[33m"
#define KBLU  "\x1B[34m"
#define KMAG  "\x1B[35m"
#define KCYN  "\x1B[36m"
#define KWHT  "\x1B[37m"

#define FRED(x) KRED x RST
#define FGRN(x) KGRN x RST
#define FYEL(x) KYEL x RST
#define FBLU(x) KBLU x RST
#define FMAG(x) KMAG x RST
#define FCYN(x) KCYN x RST
#define FWHT(x) KWHT x RST

#define BOLD(x) "\x1B[1m" x RST
#define UNDL(x) "\x1B[4m" x RST

#endif  /* _COLORS_ */

An example using the macros of the header could be:

#include <iostream>
#include "colors.h"
using namespace std;

int main()
{
    cout << FBLU("I'm blue.") << endl;
    cout << BOLD(FBLU("I'm blue-bold.")) << endl;
    return 0;
}

enter image description here

gon1332
  • 1,930
  • 1
  • 24
  • 30
39

From my understanding, a typical ANSI color code

"\033[{FORMAT_ATTRIBUTE};{FORGROUND_COLOR};{BACKGROUND_COLOR}m{TEXT}\033[{RESET_FORMATE_ATTRIBUTE}m"

is composed of (name and codec)

  • FORMAT ATTRIBUTE

     { "Default", "0" },
     { "Bold", "1" },
     { "Dim", "2" },
     { "Italics", "3"},
     { "Underlined", "4" },
     { "Blink", "5" },
     { "Reverse", "7" },
     { "Hidden", "8" }
    
  • FORGROUND COLOR

     { "Default", "39" },
     { "Black", "30" },
     { "Red", "31" },
     { "Green", "32" },
     { "Yellow", "33" },
     { "Blue", "34" },
     { "Magenta", "35" },
     { "Cyan", "36" },
     { "Light Gray", "37" },
     { "Dark Gray", "90" },
     { "Light Red", "91" },
     { "Light Green", "92" },
     { "Light Yellow", "93" },
     { "Light Blue", "94" },
     { "Light Magenta", "95" },
     { "Light Cyan", "96" },
     { "White", "97" }
    
  • BACKGROUND COLOR

     { "Default", "49" },
     { "Black", "40" },
     { "Red", "41" },
     { "Green", "42" },
     { "Yellow", "43" },
     { "Blue", "44" },
     { "Megenta", "45" },
     { "Cyan", "46" },
     { "Light Gray", "47" },
     { "Dark Gray", "100" },
     { "Light Red", "101" },
     { "Light Green", "102" },
     { "Light Yellow", "103" },
     { "Light Blue", "104" },
     { "Light Magenta", "105" },
     { "Light Cyan", "106" },
     { "White", "107" }
    
  • TEXT

  • RESET FORMAT ATTRIBUTE

     { "All", "0" },
     { "Bold", "21" },
     { "Dim", "22" },
     { "Underlined", "24" },
     { "Blink", "25" },
     { "Reverse", "27" },
     { "Hidden", "28" }
    

With this information, it is easy to colorize a string "I am a banana!" with forground color "Yellow" and background color "Green" like this

"\033[0;33;42mI am a Banana!\033[0m"

Or with a C++ library colorize

auto const& colorized_text = color::rize( "I am a banana!", "Yellow", "Green" );
std::cout << colorized_text << std::endl;

More examples with FORMAT ATTRIBUTE hereenter image description here

mTvare
  • 327
  • 1
  • 2
  • 14
Feng Wang
  • 1,506
  • 15
  • 17
20

I use the following solution, it's quite simple and elegant, can be easily pasted into source, and works on Linux/Bash:

const std::string red("\033[0;31m");
const std::string green("\033[1;32m");
const std::string yellow("\033[1;33m");
const std::string cyan("\033[0;36m");
const std::string magenta("\033[0;35m");
const std::string reset("\033[0m");

std::cout << "Measured runtime: " << yellow << timer.count() << reset << std::endl;
Daniel Langr
  • 22,196
  • 3
  • 50
  • 93
14

This is an old topic, but I wrote a class with nested subclasses and static members for colors defined by simple C macros.

I got the color function from this post Color Text In C Programming in dreamincode.net by user no2pencil.

I made it this way so to be able to use the static constants in std::cout stream like this:

cout << zkr::cc::fore::red << "This is red text. " 
     << zkr::cc::console << "And changing to console default colors, fg, bg."
     << endl;

The class and a test program source code can be downloaded here.

cc::console will reset to console default colors and attributes, cc::underline will underline the text, which works on putty which I've tested the test program.

Colors:

black
blue
red
magenta
green
cyan
yellow
white

lightblack
lightblue
lightred
lightmagenta
lightgreen
lightcyan
lightyellow
lightwhite

Which can be used with both fore and back static subclasses of the cc static class.

EDIT 2017

I'm just adding the class code here to be more practical.

The color code macros:

#define CC_CONSOLE_COLOR_DEFAULT "\033[0m"
#define CC_FORECOLOR(C) "\033[" #C "m"
#define CC_BACKCOLOR(C) "\033[" #C "m"
#define CC_ATTR(A) "\033[" #A "m"

and the main color function that defines a color or an attribute to the screen:

char *cc::color(int attr, int fg, int bg)
{
    static char command[13];

    /* Command is the control command to the terminal */
    sprintf(command, "%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40);
    return command;
}

ccolor.h

#include <stdio.h>

#define CC_CONSOLE_COLOR_DEFAULT "\033[0m"
#define CC_FORECOLOR(C) "\033[" #C "m"
#define CC_BACKCOLOR(C) "\033[" #C "m"
#define CC_ATTR(A) "\033[" #A "m"

namespace zkr
{
    class cc
    {
    public:

        class fore
        {
        public:
            static const char *black;
            static const char *blue;
            static const char *red;
            static const char *magenta;
            static const char *green;
            static const char *cyan;
            static const char *yellow;
            static const char *white;
            static const char *console;

            static const char *lightblack;
            static const char *lightblue;
            static const char *lightred;
            static const char *lightmagenta;
            static const char *lightgreen;
            static const char *lightcyan;
            static const char *lightyellow;
            static const char *lightwhite;
        };

        class back
        {
        public:
            static const char *black;
            static const char *blue;
            static const char *red;
            static const char *magenta;
            static const char *green;
            static const char *cyan;
            static const char *yellow;
            static const char *white;
            static const char *console;

            static const char *lightblack;
            static const char *lightblue;
            static const char *lightred;
            static const char *lightmagenta;
            static const char *lightgreen;
            static const char *lightcyan;
            static const char *lightyellow;
            static const char *lightwhite;
        };

        static char *color(int attr, int fg, int bg);
        static const char *console;
        static const char *underline;
        static const char *bold;
    };
}

ccolor.cpp

#include "ccolor.h"

using namespace std;

namespace zkr
{
    enum Color
    {
        Black,
        Red,
        Green,
        Yellow,
        Blue,
        Magenta,
        Cyan,
        White,
        Default = 9
    };

    enum Attributes
    {
        Reset,
        Bright,
        Dim,
        Underline,
        Blink,
        Reverse,
        Hidden
    };

    char *cc::color(int attr, int fg, int bg)
    {
        static char command[13];
        /* Command is the control command to the terminal */
        sprintf(command, "%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40);
        return command;
    }

    const char *cc::console = CC_CONSOLE_COLOR_DEFAULT;
    const char *cc::underline = CC_ATTR(4);
    const char *cc::bold = CC_ATTR(1);

    const char *cc::fore::black = CC_FORECOLOR(30);
    const char *cc::fore::blue = CC_FORECOLOR(34);
    const char *cc::fore::red = CC_FORECOLOR(31);
    const char *cc::fore::magenta = CC_FORECOLOR(35);
    const char *cc::fore::green = CC_FORECOLOR(92);
    const char *cc::fore::cyan = CC_FORECOLOR(36);
    const char *cc::fore::yellow = CC_FORECOLOR(33);
    const char *cc::fore::white = CC_FORECOLOR(37);
    const char *cc::fore::console = CC_FORECOLOR(39);

    const char *cc::fore::lightblack = CC_FORECOLOR(90);
    const char *cc::fore::lightblue = CC_FORECOLOR(94);
    const char *cc::fore::lightred = CC_FORECOLOR(91);
    const char *cc::fore::lightmagenta = CC_FORECOLOR(95);
    const char *cc::fore::lightgreen = CC_FORECOLOR(92);
    const char *cc::fore::lightcyan = CC_FORECOLOR(96);
    const char *cc::fore::lightyellow = CC_FORECOLOR(93);
    const char *cc::fore::lightwhite = CC_FORECOLOR(97);

    const char *cc::back::black = CC_BACKCOLOR(40);
    const char *cc::back::blue = CC_BACKCOLOR(44);
    const char *cc::back::red = CC_BACKCOLOR(41);
    const char *cc::back::magenta = CC_BACKCOLOR(45);
    const char *cc::back::green = CC_BACKCOLOR(42);
    const char *cc::back::cyan = CC_BACKCOLOR(46);
    const char *cc::back::yellow = CC_BACKCOLOR(43);
    const char *cc::back::white = CC_BACKCOLOR(47);
    const char *cc::back::console = CC_BACKCOLOR(49);

    const char *cc::back::lightblack = CC_BACKCOLOR(100);
    const char *cc::back::lightblue = CC_BACKCOLOR(104);
    const char *cc::back::lightred = CC_BACKCOLOR(101);
    const char *cc::back::lightmagenta = CC_BACKCOLOR(105);
    const char *cc::back::lightgreen = CC_BACKCOLOR(102);
    const char *cc::back::lightcyan = CC_BACKCOLOR(106);
    const char *cc::back::lightyellow = CC_BACKCOLOR(103);
    const char *cc::back::lightwhite = CC_BACKCOLOR(107);
}
Christos Lytras
  • 36,310
  • 4
  • 80
  • 113
  • 2
    Thanks for the code. I added another [ANSI escape code](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors) to allow displaying bold text: `const char *cc::bold = CC_ATTR(1);` – Drew Noakes Nov 17 '13 at 17:21
  • Thanks for the addition. I have included this to the class code. – Christos Lytras Dec 04 '13 at 09:18
12

An expanded version of gon1332's header:

//
//  COLORS.h
//
//  Posted by Gon1332 May 15 2015 on StackOverflow
//  https://stackoverflow.com/questions/2616906/how-do-i-output-coloured-text-to-a-linux-terminal#2616912
//
//  Description: An easy header file to make colored text output to terminal second nature.
//  Modified by Shades Aug. 14 2018

// PLEASE carefully read comments before using this tool, this will save you a lot of bugs that are going to be just about impossible to find.
#ifndef COLORS_h
#define COLORS_h

/* FOREGROUND */
// These codes set the actual text to the specified color
#define RESETTEXT  "\x1B[0m" // Set all colors back to normal.
#define FOREBLK  "\x1B[30m" // Black
#define FORERED  "\x1B[31m" // Red
#define FOREGRN  "\x1B[32m" // Green
#define FOREYEL  "\x1B[33m" // Yellow
#define FOREBLU  "\x1B[34m" // Blue
#define FOREMAG  "\x1B[35m" // Magenta
#define FORECYN  "\x1B[36m" // Cyan
#define FOREWHT  "\x1B[37m" // White

/* BACKGROUND */
// These codes set the background color behind the text.
#define BACKBLK "\x1B[40m"
#define BACKRED "\x1B[41m"
#define BACKGRN "\x1B[42m"
#define BACKYEL "\x1B[43m"
#define BACKBLU "\x1B[44m"
#define BACKMAG "\x1B[45m"
#define BACKCYN "\x1B[46m"
#define BACKWHT "\x1B[47m"

// These will set the text color and then set it back to normal afterwards.
#define BLK(x) FOREBLK x RESETTEXT
#define RED(x) FORERED x RESETTEXT
#define GRN(x) FOREGRN x RESETTEXT
#define YEL(x) FOREYEL x RESETTEXT
#define BLU(x) FOREBLU x RESETTEXT
#define MAG(x) FOREMAG x RESETTEXT
#define CYN(x) FORECYN x RESETTEXT
#define WHT(x) FOREWHT x RESETTEXT

// Example usage: cout << BLU("This text's color is now blue!") << endl;

// These will set the text's background color then reset it back.
#define BackBLK(x) BACKBLK x RESETTEXT
#define BackRED(x) BACKRED x RESETTEXT
#define BackGRN(x) BACKGRN x RESETTEXT
#define BackYEL(x) BACKYEL x RESETTEXT
#define BackBLU(x) BACKBLU x RESETTEXT
#define BackMAG(x) BACKMAG x RESETTEXT
#define BackCYN(x) BACKCYN x RESETTEXT
#define BackWHT(x) BACKWHT x RESETTEXT

// Example usage: cout << BACKRED(FOREBLU("I am blue text on a red background!")) << endl;

// These functions will set the background to the specified color indefinitely.
// NOTE: These do NOT call RESETTEXT afterwards. Thus, they will set the background color indefinitely until the user executes cout << RESETTEXT
// OR if a function is used that calles RESETTEXT i.e. cout << RED("Hello World!") will reset the background color since it calls RESETTEXT.
// To set text COLOR indefinitely, see SetFore functions below.
#define SetBackBLK BACKBLK
#define SetBackRED BACKRED
#define SetBackGRN BACKGRN
#define SetBackYEL BACKYEL
#define SetBackBLU BACKBLU
#define SetBackMAG BACKMAG
#define SetBackCYN BACKCYN
#define SetBackWHT BACKWHT

// Example usage: cout << SetBackRED << "This text's background and all text after it will be red until RESETTEXT is called in some way" << endl;

// These functions will set the text color until RESETTEXT is called. (See above comments)
#define SetForeBLK FOREBLK
#define SetForeRED FORERED
#define SetForeGRN FOREGRN
#define SetForeYEL FOREYEL
#define SetForeBLU FOREBLU
#define SetForeMAG FOREMAG
#define SetForeCYN FORECYN
#define SetForeWHT FOREWHT

// Example usage: cout << SetForeRED << "This text and all text after it will be red until RESETTEXT is called in some way" << endl;

#define BOLD(x) "\x1B[1m" x RESETTEXT // Embolden text then reset it.
#define BRIGHT(x) "\x1B[1m" x RESETTEXT // Brighten text then reset it. (Same as bold but is available for program clarity)
#define UNDL(x) "\x1B[4m" x RESETTEXT // Underline text then reset it.

// Example usage: cout << BOLD(BLU("I am bold blue text!")) << endl;

// These functions will embolden or underline text indefinitely until RESETTEXT is called in some way.

#define SetBOLD "\x1B[1m" // Embolden text indefinitely.
#define SetBRIGHT "\x1B[1m" // Brighten text indefinitely. (Same as bold but is available for program clarity)
#define SetUNDL "\x1B[4m" // Underline text indefinitely.

// Example usage: cout << setBOLD << "I and all text after me will be BOLD/Bright until RESETTEXT is called in some way!" << endl;

#endif /* COLORS_h */

As you can see, it has more capabilities such as the ability to set background color temporarily, indefinitely, and other features. I also believe it is a bit more beginner friendly and easier to remember all of the functions.

#include <iostream>
#include "COLORS.h"

int main() {
  std::cout << SetBackBLU << SetForeRED << endl;
  std::cout << "I am red text on a blue background! :) " << endl;
  return 0;
}

Simply include the header file in your project and you're ready to rock and roll with the colored terminal output.

Dinesh Reddy
  • 775
  • 1
  • 11
  • 25
Shades
  • 667
  • 1
  • 7
  • 22
10

You can use escape sequences, if your terminal supports it. For example:

echo \[\033[32m\]Hello, \[\033[36m\]colourful \[\033[33mworld!\033[0m\]
Martin York
  • 257,169
  • 86
  • 333
  • 562
Vlad
  • 35,022
  • 6
  • 77
  • 199
3

try my header here for a quick and easy way to color text: Aedi's Color Header


Escape-Sequence-Color-Header

Color Your Output in Unix using C++!!


Text Attribute Options:

ATTRIBUTES_OFF, BOLD, UNDERSCORE, BLINK, REVERSE_VIDEO, CONCEALED


Color Options:

BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE


Format:

General Format, include value you want in $variable$

COLOR_$Foreground_Color$_$Background_Color$
COLOR_$Text_Attribute$_$Foreground_Color$_$Background_Color$
COLOR_NORMAL  // To set color to default

e.g.

COLOR_BLUE_BLACK // Leave Text Attribute Blank if no Text Attribute appied
COLOR_UNDERSCORE_YELLOW_RED
COLOR_NORMAL


Usage:

Just use to stream the color you want before outputting text and use again to set the color to normal after outputting text.

cout << COLOR_BLUE_BLACK << "TEXT" << COLOR_NORMAL << endl;
cout << COLOR_BOLD_YELLOW_CYAN << "TEXT" << COLOR_NORMAL << endl;
Uduse
  • 1,491
  • 1
  • 13
  • 18
3

You can use ANSI colour codes.

use these functions.

enum c_color{BLACK=30,RED=31,GREEN=32,YELLOW=33,BLUE=34,MAGENTA=35,CYAN=36,WHITE=37};
enum c_decoration{NORMAL=0,BOLD=1,FAINT=2,ITALIC=3,UNDERLINE=4,RIVERCED=26,FRAMED=51};
void pr(const string str,c_color color,c_decoration decoration=c_decoration::NORMAL){
  cout<<"\033["<<decoration<<";"<<color<<"m"<<str<<"\033[0m";
}

void prl(const string str,c_color color,c_decoration decoration=c_decoration::NORMAL){
   cout<<"\033["<<decoration<<";"<<color<<"m"<<str<<"\033[0m"<<endl;
}
Shanaka Rusith
  • 421
  • 1
  • 4
  • 19
2

on OSX shell, this works for me (including 2 spaces in front of "red text"):

$ printf "\e[033;31m  red text\n"
$ echo "$(tput setaf 1)  red text"
BananaAcid
  • 3,221
  • 35
  • 38
2

The best way is to use the ncurses library - though this might be a sledgehammer to crack a nut if you just want to output a simple coloured string

Nick
  • 2,012
  • 1
  • 13
  • 10
0

I wrote a cross-platform library color_ostream for this, with the support of ANSI color, 256 color and true color, all you have to do is directly including it and changing cout to rd_cout like this.

std basic color 256 color true color
std::cout color_ostream::rd_cout color_ostream::rd256_cout color_ostream::rdtrue_cout
std::wcout color_ostream::rd_wcout color_ostream::rd256_wcout color_ostream::rdtrue_wcout
std::cerr color_ostream::rd_cerr color_ostream::rd256_cerr color_ostream::rdtrue_cerr
std::wcerr color_ostream::rd_wcerr color_ostream::rd256_wcerr color_ostream::rdtrue_wcerr
std::clog color_ostream::rd_clog color_ostream::rd256_clog color_ostream::rdtrue_clog
std::wclog color_ostream::rd_wclog color_ostream::rd256_wclog color_ostream::rdtrue_wclog

Here is an simple example:

//hello.cpp
#include "color_ostream.h"

using namespace color_ostream;

int main([[maybe_unused]] int argc, [[maybe_unused]] char *argv[]) {
    rd_wcout.imbue(std::locale(std::locale(),"",LC_CTYPE));
    rd_wcout << L"Hello world\n";
    rd_wcout << L"Hola Mundo\n";
    rd_wcout << L"Bonjour le monde\n";

    rd256_wcout << L"\n256 color" << std::endl;
    rd256_wcout << L"Hello world\n";
    rd256_wcout << L"Hola Mundo\n";
    rd256_wcout << L"Bonjour le monde\n";

    rdtrue_wcout << L"\ntrue color" << std::endl;
    rdtrue_wcout << L"Hello world\n";
    rdtrue_wcout << L"Hola Mundo\n";
    rdtrue_wcout << L"Bonjour le monde\n";
    return 0;
}
kHarshit
  • 11,362
  • 10
  • 52
  • 71
Wongboo
  • 124
  • 1
  • 6
0

You can either write ANSI escape codes that control color directly or use a library such as {fmt} that provides APIs for this.

For example:

#include <fmt/color.h>

int main() { 
  fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold,
             "Hello, {}!\n", "world");
}

prints

"Hello, world!" in crimson and bold

Most modern terminals support ANSI escape sequences but you can use the terminfo database to check.

vitaut
  • 49,672
  • 25
  • 199
  • 336
0

I am aware that this question is old but i am posting this answer for future readers. I have written a library for colored output in c++. This uses manipulators that makes work easy supports cross platform but not tested here is over view how to use this,

#include "srilakshmikanthanp/ANSI.hpp"

using namespace srilakshmikanthanp;

3 and 4 bit colors:

// background
std::cout << ansi::BGyellow;
// foreground
std::cout << ansi::FGblue;
// output
std::cout << "Blue on yellow";
// reset
std::cout << ansi::reset;

8 bit color:

// background
std::cout << ansi::BGcolor(157);
// foreground
std::cout << ansi::FGcolor(100);
// outpt
std::cout << "8 bit color";
// reset
std::cout << ansi::reset;

24 bit color:

// background
std::cout << ansi::BGcolor(0, 255, 0);
// foreground
std::cout << ansi::FGcolor(0, 0, 255);
// output
std::cout << "24 bit color";
// reset
std::cout << ansi::reset;

to string:

You can easily convert this manipulators to string by using ansi::str

std::string BGyellow = ansi::str(ansi::BGyellow);
std::string FGblue = ansi::str(ansi::FGblue);
std::string reset = ansi::str(ansi::reset);

std::cout << BGyelow;
// foreground
std::cout << FGblue;
// output
std::cout << "Blue on Yellow";
// reset
std::cout << reset;

You can find more info in the github with above link :)

srilakshmikanthanp
  • 2,231
  • 1
  • 8
  • 25