Jak wydrukować kolorowy tekst na terminalu Linuksa?

Jak wydrukować kolorowe znaki na obsługiwanym przez Linuksa terminalu?

Jak sprawdzić, czy terminal obsługuje kody kolorów?

Author: Rakete1111, 2010-04-11

14 answers

Musisz wypisać kody kolorów ANSI . Zauważ, że nie wszystkie terminale to obsługują; jeśli sekwencje kolorów nie są obsługiwane, pojawią się śmieci.

Przykład:

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

Tutaj, \033 jest znak ESC, ASCII 27. Po nim następuje [, Następnie zero lub więcej cyfr oddzielonych ;, a na końcu litera m. Liczby opisują kolor i format, na który należy przejść od tego momentu.

Kody kolorów pierwszoplanowych i tła są:

         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

Dodatkowo możesz użyć tych:

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

Zobacz tabelę na Wikipedii {[15] } dla innych, mniej powszechnie obsługiwanych kodów.


Aby określić, czy twój terminal obsługuje sekwencje kolorów, przeczytaj wartość zmiennej środowiskowej TERM. Powinien on określać określony typ terminala (np. vt100, gnome-terminal, xterm, screen, ...). Następnie sprawdź to w bazie danych terminfo ; sprawdź możliwości colors.

 452
Author: Thomas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-18 19:56:28

Podstawy

Napisałem klasę C++, która może być używana do ustawiania koloru pierwszego planu i tła wyjścia. Ten przykładowy program służy jako przykład drukowania This ->word<- is red. i formatowania go tak, aby kolor pierwszoplanowy word był czerwony.

#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;
}

Źródło

#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";
        }
    };
}

Zaawansowane

Możesz chcieć dodać dodatkowe funkcje do klasy. Można na przykład dodać kolor magenta, a nawet style, takie jak boldface. Aby to zrobić, wystarczy kolejny wpis do Code wyliczenie. to jest dobrym odniesieniem.

 103
Author: Joel Sjögren,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-04 13:30:37

Zanim zaczniesz wyświetlać dowolny kolor, upewnij się, że jesteś w terminalu:

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

Następnie należy sprawdzić zdolność terminala, jeśli obsługuje kolor

W systemach z terminfo (oparte na Linuksie) możesz uzyskać ilość obsługiwanych kolorów jako

Number_Of_colors_Supported=$(tput colors)

W systemach z termcap (BSD) można uzyskać ilość obsługiwanych kolorów jako

Number_Of_colors_Supported=$(tput Co)

Następnie podjąć decyzję:

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

BTW, nie używaj kolorowania jak było sugerowane wcześniej ze znakami ESC. Użyj standardowej funkcji wywołania do terminala, która przypisze Ci poprawne kolory, które obsługują dany terminal.

Oparte na BSD
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)"
Oparty Na Linuksie
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)"
Użyj Jako
echo -e "${fg_red}  Red  ${fg_green} Bull ${reset}"
 44
Author: Alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-10 22:34:14

Jak stwierdzili inni, możesz używać znaków ucieczki. Możesz użyć Mój nagłówek w celu ułatwienia:

#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_ */

Przykładem użycia makr nagłówka może być:

#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;
}

Tutaj wpisz opis obrazka

 37
Author: gon1332,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-22 11:18:40

Z mojego zrozumienia, typowy kod koloru ANSI

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

Składa się z (nazwa i kodek)

  • ATRYBUT FORMATU

    { "Default", "0" },
    { "Bold", "1" },
    { "Dim", "2" },
    { "Underlined", "3" },
    { "Blink", "5" },
    { "Reverse", "7" },
    { "Hidden", "8" }
    
  • FORWARD 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" }
    
  • KOLOR TŁA

    { "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" }
    
  • Tekst

  • RESETOWANIE ATRYBUTU FORMATU

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

Dzięki tej informacji łatwo jest pokolorować napis "jestem bananem!"z forground kolor "żółty" i kolor tła "Zielony" jak to

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

Lub z biblioteką C++ colorize

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

Więcej przykładów z atrybutem FORMAT tutajTutaj wpisz opis obrazka

 20
Author: Feng Wang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-25 10:37:34

Używam następującego rozwiązania, jest dość proste i eleganckie, można je łatwo wkleić do źródła i działa na Linuksie / 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;
 16
Author: Daniel Langr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-01 08:23:48

To stary temat, ale napisałem klasę z zagnieżdżonymi podklasami i statycznymi członkami dla kolorów zdefiniowanych przez proste makra C.

Dostałem color funkcję z tego posta kolorowy tekst w programowaniu C w dreamincode.net przez użytkownika no2pencil.

Zrobiłem to tak, aby móc używać stałych statycznych w strumieniu std:: cout w następujący sposób:

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

Klasa i Kod źródłowy programu testowego można pobrać tutaj .

cc::console resetuje się do domyślne kolory i atrybuty konsoli, cc::underline podkreślą tekst, który działa na putty, który przetestowałem program testowy.

Kolory:

black
blue
red
magenta
green
cyan
yellow
white

lightblack
lightblue
lightred
lightmagenta
lightgreen
lightcyan
lightyellow
lightwhite

, który może być używany zarówno z fore, jak i back statycznymi podklasami klasy cc static.

EDIT 2017

Dodaję tutaj Kod klasowy, aby być bardziej praktycznym.

Makra kodu kolorów:

#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"

Oraz główna funkcja koloru, która definiuje kolor lub atrybut do ekran:

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);
}
 14
Author: Christos Lytras,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-10 08:41:11

Możesz użyć sekwencji escape, jeśli twój terminal ją obsługuje. Na przykład:

echo \[\033[32m\]Hello, \[\033[36m\]colourful \[\033[33mworld!\033[0m\]
 9
Author: Vlad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-21 13:57:43

Rozszerzona wersja nagłówka gon1332:

//
//  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 */

Jak widać, ma więcej możliwości, takich jak możliwość ustawiania koloru tła tymczasowo, na czas nieokreślony i inne funkcje. Uważam również, że jest nieco bardziej przyjazny dla początkujących i łatwiej zapamiętać wszystkie funkcje.

#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;
}

Po prostu dołącz plik nagłówka do projektu i jesteś gotowy do rock and roll z kolorowym wyjściem terminala.

 9
Author: Shades,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-24 10:44:55

Wypróbuj mój nagłówek tutaj, aby szybko i łatwo pokolorować tekst: kolor nagłówka Aedi


Escape-Sequence-Color-Header

Pokoloruj swoje wyjście w Uniksie używając C++!!


Opcje Atrybutów Tekstu:

ATTRIBUTES_OFF, BOLD, UNDERSCORE, BLINK, REVERSE_VIDEO, CONCEALED


Opcje Kolorów:

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


Format:

Ogólny Format, Dołącz wartość, którą chcesz w $zmienna$

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

Np.

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


Użycie:

Wystarczy użyć do przesyłania strumieniowego żądanego koloru przed wysłaniem tekstu i użyj ponownie, aby ustawić kolor normalny po wyświetleniu tekstu.

cout << COLOR_BLUE_BLACK << "TEXT" << COLOR_NORMAL << endl;
cout << COLOR_BOLD_YELLOW_CYAN << "TEXT" << COLOR_NORMAL << endl;
 3
Author: Uduse,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-04 04:46:15

Możesz użyć kodów kolorów ANSI.

Użyj tych funkcji.

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;
}
 3
Author: Shanaka Rusith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-28 09:20:16

Najlepszym sposobem jest użycie biblioteki ncurses-choć może to być młot do złamania orzecha, jeśli chcesz po prostu wypisać prosty kolorowy Ciąg

 2
Author: Nick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-04-23 16:22:12

Na powłoce OSX działa mi to (w tym 2 spacje przed "czerwonym tekstem"):

$ printf "\e[033;31m  red text\n"
$ echo "$(tput setaf 1)  red text"
 2
Author: BananaAcid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-26 08:22:53

Napisałem do tego wieloplatformową bibliotekę color_ostream , z obsługą ANSI color, 256 color I true color, wszystko, co musisz zrobić, to bezpośrednio włączyć ją i zmienić cout na rd_cout w ten sposób.
/ 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 |
Oto prosty przykład:

//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;
}
 0
Author: Wongboo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-01 01:35:47