【问题标题】:How do I output coloured text to a Linux terminal?如何将彩色文本输出到 Linux 终端?
【发布时间】:2011-02-06 16:43:48
【问题描述】:

如何将彩色字符打印到支持它的 Linux 终端?

如何判断终端是否支持色码?

【问题讨论】:

  • 要确定终端的能力,请检查终端能力数据库。见termcap(5)
  • 随意查看我输入的代码 sn-p here。这是一个小工具,可借助一些宏为其输出着色。
  • "termcap 数据库是用于描述字符单元终端和打印机功能的过时工具。它仅用于旧程序的功能;新程序应使用terminfo(5) 数据库和相关库。” -- termcap(5)
  • 你可以轻松termcolor
  • 如果你想用彩色打印做一些高级的东西,我建议你阅读this的文章。我发现它很有帮助

标签: c++ linux colors terminal


【解决方案1】:

你需要输出ANSI colour codes。请注意,并非所有终端都支持此功能;如果不支持颜色序列,则会显示垃圾。

例子:

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

这里,\033 是 ESC 字符,ASCII 27。紧随其后的是 [,然后是由 ; 分隔的零个或多个数字,最后是字母 m。这些数字描述了从该点开始切换到的颜色和格式。

前景色和背景色的代码是:

         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

此外,您还可以使用这些:

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

请参阅table on Wikipedia 了解其他不太广泛支持的代码。


要确定您的终端是否支持颜色序列,请读取TERM 环境变量的值。它应该指定使用的特定终端类型(例如vt100gnome-terminalxtermscreen、...)。然后在terminfo database 中查找;检查colors 功能。

【讨论】:

  • 这是 BBS 上的蜜蜂膝盖……
  • m 代表什么?
  • @nipponese \033[m 标记 ANSI 颜色代码的转义序列的开始和结束。参考:en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes
  • 我用它来定义“操纵器”,例如const std::string red("\033[0;31m");const std::string reset("\033[0m");。然后,我可以简单地写cout &lt;&lt; red &lt;&lt; "red text" &lt;&lt; reset &lt;&lt; endl;
  • 我想看看这个颜色的可视化:misc.flogisoft.com/bash/tip_colors_and_formatting
【解决方案2】:

基础知识

我写了一个 C++ 类,可以用来设置输出的前景色和背景色。此示例程序用作打印This -&gt;word&lt;- is red. 并对其进行格式化以使word 的前景色为红色的示例。

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

来源

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

高级

您可能想为课程添加其他功能。例如,可以添加洋红色,甚至可以添加 boldface 等样式。为此,只需在Code 枚举中添加一个条目。 This 是一个很好的参考。

【讨论】:

  • 太棒了‌‌‌‌‌‌‌‌‌‌‌‌。如果您可以添加其他颜色和背景颜色,将会很有帮助。
  • 更多:`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_ULTUE = 494
  • 如果你定义operator&lt;&lt;Code,那么你可以直接写std::cout &lt;&lt; Color::FG_RED;而不是std::cout &lt;&lt; Modifier(Color::FG_RED);。也就是说,不需要Modifier
  • @Nawaz 好主意。这是一个这样的实现:pastebin.com/zWC3t9hC。但是我会在答案中保留我的原始实现,因为我觉得它更具可扩展性。
  • 其实我更喜欢第一个实现,因为您可以添加一个标志来打开或关闭颜色:将bool sh; 添加到类并将构造函数更改为Modifier (Code pCode, bool show = true) : code(pCode), sh(show) {}。最后,在&lt;&lt; 运算符的主体中返回当前行if (sh)return &lt;&lt; os; 否则。这允许使用Color::Modifier red(Color::FG_RED, BoolVar); 编写代码,您可以将BoolVar 设置为true 或false 作为程序的初始化。您可以打开它以在屏幕上看到它,关闭它以重定向到一个文件。
【解决方案3】:

在您输出任何所需的颜色之前,请确保您在终端中:

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

那么你需要检查终端能力是否支持颜色

在带有terminfo的系统上(基于Linux)你可以获得支持的颜色数量

Number_Of_colors_Supported=$(tput colors)

在带有termcap的系统上(基于BSD)您可以获得支持的颜色数量

Number_Of_colors_Supported=$(tput Co)

然后做出决定:

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

顺便说一句,不要像以前建议的那样使用 ESC 字符着色。 使用标准调用终端功能,为您分配特定终端支持的正确颜色。

基于 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)"
基于 Linux
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)"
用于
echo -e "${fg_red}  Red  ${fg_green} Bull ${reset}"

【讨论】:

  • 这不是特定于 bash 的吗? -t 1 显然在 C++ 中不起作用,在 C++ 程序中调用这个 tput 程序会使其非常迂回。
  • @Macha,是的,[ -t 1 ] 它是特定于 sh/bash 的,但在 #(comment) 符号之后的右侧有 C 函数可以执行相同的操作。 man 3 isatty 应该对此有所帮助;)示例显示为 shell 命令以简化对要点的解释。至于tput,它是查询标准终端能力接口的开源实用程序。
  • 我不知道为什么人们一直建议直接使用这些代码。做出这样的假设是非常非常糟糕的做法。即使这是特定于 shell 的代码,任何有 shell 经验的人都可以翻译它。
  • tput 是该死的 slow 使用 C++,例如在 REPL 实现中(每个可能需要 0.06 秒,而通常具有动态系统库的 C++ 进程在启动和终止中的总开销为 0.02 秒)。而且它仍然不是 那个 可移植的:ANSI 转义码但不是tput 可以在某些新版本的 Windows 10 或启用了钩子的 ConEmu 上正常工作。即使tput 可用,它仍然需要关心terminfotermcap 之间的差异。
  • 其实我就是来找my implementation in C++的改进的。似乎没有人已经在 C/C++ 中手动内联 tput 调用...
【解决方案4】:

正如其他人所说,您可以使用转义字符。 您可以使用my header 以使其更容易:

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

使用标头宏的示例可能是:

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

【讨论】:

  • 标题很棒!
【解决方案5】:

据我了解,典型的 ANSI 颜色代码

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

由(名称和编解码器)组成

  • 格式属性

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

     { "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" }
    
  • 背景颜色

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

  • 重置格式属性

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

有了这些信息,就可以很容易地为字符串“我是香蕉!”着色。像这样使用前景色“黄色”和背景色“绿色”

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

或者使用 C++ 库colorize

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

更多使用 FORMAT ATTRIBUTE 的例子

【讨论】:

  • 这好多了,我可以在我的 PHP C++ 扩展中使用它。
  • 好吧,我知道你是香蕉!
  • 与上面的高分答案基本相同,但更容易理解和更详细。从我这边投票。我真的很喜欢“眨眼”。世界准备好看到闪烁的终端!
  • 实用又美观。非常感谢您的贡献,先生。
【解决方案6】:

我使用以下解决方案,它非常简单优雅,可以轻松粘贴到源代码中,并且适用于 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;

【讨论】:

    【解决方案7】:

    这是一个老话题,但我编写了一个包含嵌套子类和静态成员的类,用于由简单的 C 宏定义的颜色。

    我从用户 no2pencil 在 dreamincode.net 中的这篇帖子 Color Text In C Programming 中获得了 color 函数。

    我这样做是为了能够像这样在 std::cout 流中使用静态常量:

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

    该类和一个测试程序源代码可以在here下载。

    cc::console 将重置为控制台默认颜色和属性,cc::underline 将在文本下划线,这适用于我测试过的测试程序的 putty。

    颜色:

    black
    blue
    red
    magenta
    green
    cyan
    yellow
    white
    
    lightblack
    lightblue
    lightred
    lightmagenta
    lightgreen
    lightcyan
    lightyellow
    lightwhite
    

    它可以与cc 静态类的foreback 静态子类一起使用。

    2017 年编辑

    我只是在这里添加类代码更实用。

    颜色代码宏:

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

    以及定义屏幕颜色或属性的主要颜色函数:

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

    【讨论】:

    • 感谢您的代码。我添加了另一个ANSI escape code 以允许显示粗体文本:const char *cc::bold = CC_ATTR(1);
    • 感谢您的加入。我已将其包含在课程代码中。
    【解决方案8】:

    如果您的终端支持,您可以使用转义序列。例如:

    echo \[\033[32m\]Hello, \[\033[36m\]colourful \[\033[33mworld!\033[0m\]
    

    【讨论】:

      【解决方案9】:

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

      如您所见,它具有更多功能,例如可以临时、无限期设置背景颜色等功能。我也相信它对初学者更友好,更容易记住所有功能。

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

      只需将头文件包含在您的项目中,您就可以使用彩色终端输出进行摇滚了。

      【讨论】:

        【解决方案10】:

        在此处尝试我的标题以快速简便地为文本着色:Aedi's Color Header


        转义序列颜色标题

        使用 C++ 在 Unix 中为您的输出着色!!


        文本属性选项:

        ATTRIBUTES_OFF, BOLD, UNDERSCORE, BLINK, REVERSE_VIDEO, CONCEALED
        


        颜色选项:

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


        格式:

        通用格式,在$variable$中包含你想要的值

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

        例如

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


        用法:

        只需在输出文本之前使用流式传输所需的颜色和 输出文本后再次使用,将颜色设置为正常。

        cout << COLOR_BLUE_BLACK << "TEXT" << COLOR_NORMAL << endl;
        cout << COLOR_BOLD_YELLOW_CYAN << "TEXT" << COLOR_NORMAL << endl;
        

        【讨论】:

        • 这是一个仅链接的答案,如果链接断开,它将变得无用。请添加一些代码或详细说明您的答案
        • 对不起,这里的新手...刚刚添加了更多信息。做这项工作?
        • @sjm324 我猜是否支持BLINK取决于你的系统
        【解决方案11】:

        您可以使用 ANSI 颜色代码。

        使用这些功能。

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

        【讨论】:

          【解决方案12】:

          最好的方法是使用 ncurses 库 - 虽然如果你只想输出一个简单的彩色字符串,这可能是一把大锤来破解坚果

          【讨论】:

          • @Nick 使用 ncurses 来通过 echo 实现一些着色会很痛苦。 :)
          【解决方案13】:

          在 OSX shell 上,这对我有用(包括“红色文本”前面的 2 个空格):

          $ printf "\e[033;31m  red text\n"
          $ echo "$(tput setaf 1)  red text"
          

          【讨论】:

            【解决方案14】:

            您可以编写直接控制颜色的ANSI escape codes,也可以使用为此提供API 的库,例如{fmt}

            例如:

            #include <fmt/color.h>
            
            int main() { 
              fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold,
                         "Hello, {}!\n", "world");
            }
            

            打印

            大多数现代终端都支持 ANSI 转义序列,但您可以使用 terminfo 数据库进行检查。

            【讨论】:

              【解决方案15】:

              我知道这个问题很老,但我将这个答案发布给未来的读者。我已经为 C++ 中的彩色输出写了一个library。这使用了使工作变得容易的操纵器,支持跨平台但未测试这里是概述如何使用它,

              #include "srilakshmikanthanp/ANSI.hpp"
              
              using namespace srilakshmikanthanp;
              

              3 位和 4 位颜色:

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

              8 位颜色:

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

              24 位颜色:

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

              转字符串:

              您可以使用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;
              

              您可以通过上面的链接在 github 中找到更多信息 :)

              【讨论】:

                【解决方案16】:

                为此我写了一个跨平台库color_ostream,支持ANSI色、256色和真彩色,你只需要直接包含它,像这样把cout改成rd_cout。

                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

                这是一个简单的例子:

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

                【讨论】:

                • 我的图表显示不正确,有人帮帮我吗?
                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2010-09-22
                • 1970-01-01
                • 1970-01-01
                • 2011-07-22
                • 1970-01-01
                • 2021-07-18
                相关资源
                最近更新 更多