猿问

如何将彩色文本输出到Linux终端?

如何将彩色文本输出到Linux终端?

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

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


富国沪深
浏览 621回答 3
3回答

湖上湖

基本我编写了一个C ++类,可用于设置输出的前景色和背景色。此示例程序用作打印This ->word<- is red.和格式化它的示例,以使前景色word为红色。#include "colormod.h" // namespace Color#include <iostream>using namespace std;int main() {&nbsp; &nbsp; Color::Modifier red(Color::FG_RED);&nbsp; &nbsp; Color::Modifier def(Color::FG_DEFAULT);&nbsp; &nbsp; cout << "This ->" << red << "word" << def << "<- is red." << endl;}资源#include <ostream>namespace Color {&nbsp; &nbsp; enum Code {&nbsp; &nbsp; &nbsp; &nbsp; FG_RED&nbsp; &nbsp; &nbsp; = 31,&nbsp; &nbsp; &nbsp; &nbsp; FG_GREEN&nbsp; &nbsp; = 32,&nbsp; &nbsp; &nbsp; &nbsp; FG_BLUE&nbsp; &nbsp; &nbsp;= 34,&nbsp; &nbsp; &nbsp; &nbsp; FG_DEFAULT&nbsp; = 39,&nbsp; &nbsp; &nbsp; &nbsp; BG_RED&nbsp; &nbsp; &nbsp; = 41,&nbsp; &nbsp; &nbsp; &nbsp; BG_GREEN&nbsp; &nbsp; = 42,&nbsp; &nbsp; &nbsp; &nbsp; BG_BLUE&nbsp; &nbsp; &nbsp;= 44,&nbsp; &nbsp; &nbsp; &nbsp; BG_DEFAULT&nbsp; = 49&nbsp; &nbsp; };&nbsp; &nbsp; class Modifier {&nbsp; &nbsp; &nbsp; &nbsp; Code code;&nbsp; &nbsp; public:&nbsp; &nbsp; &nbsp; &nbsp; Modifier(Code pCode) : code(pCode) {}&nbsp; &nbsp; &nbsp; &nbsp; friend std::ostream&&nbsp; &nbsp; &nbsp; &nbsp; operator<<(std::ostream& os, const Modifier& mod) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return os << "\033[" << mod.code << "m";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; };}高级您可能希望为该类添加其他功能。例如,可以添加颜色洋红色甚至粗体样式。为此,只需Code枚举的另一个条目。这是一个很好的参考。

慕莱坞森

在您输出任何颜色之前,您需要确保您在终端:[&nbsp;-t&nbsp;1&nbsp;]&nbsp;&&&nbsp;echo&nbsp;'Yes&nbsp;I&nbsp;am&nbsp;in&nbsp;a&nbsp;terminal'&nbsp;&nbsp;#&nbsp;isatty(3)&nbsp;call&nbsp;in&nbsp;C然后,如果支持颜色,则需要检查终端功能在具有terminfo&nbsp;(基于Linux)的系统上,您可以获得支持的颜色数量Number_Of_colors_Supported=$(tput&nbsp;colors)在具有termcap&nbsp;(基于BSD)的系统上,您可以获得支持的颜色数量Number_Of_colors_Supported=$(tput&nbsp;Co)然后让你决定:[&nbsp;${Number_Of_colors_Supported}&nbsp;-ge&nbsp;8&nbsp;]&nbsp;&&&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;echo&nbsp;'You&nbsp;are&nbsp;fine&nbsp;and&nbsp;can&nbsp;print&nbsp;colors'}&nbsp;||&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;echo&nbsp;'Terminal&nbsp;does&nbsp;not&nbsp;support&nbsp;color'}顺便说一下,不要像以前用ESC字符那样使用着色。使用标准调用终端功能,为您分配特定终端支持的CORRECT颜色。基于BSDfg_black="$(tput&nbsp;AF&nbsp;0)"fg_red="$(tput&nbsp;AF&nbsp;1)"fg_green="$(tput&nbsp;AF&nbsp;2)"fg_yellow="$(tput&nbsp;AF&nbsp;3)"fg_blue="$(tput&nbsp;AF&nbsp;4)"fg_magenta="$(tput&nbsp;AF&nbsp;5)"fg_cyan="$(tput&nbsp;AF&nbsp;6)"fg_white="$(tput&nbsp;AF&nbsp;7)"reset="$(tput&nbsp;me)"基于Linuxfg_black="$(tput&nbsp;setaf&nbsp;0)"fg_red="$(tput&nbsp;setaf&nbsp;1)"fg_green="$(tput&nbsp;setaf&nbsp;2)"fg_yellow="$(tput&nbsp;setaf&nbsp;3)"fg_blue="$(tput&nbsp;setaf&nbsp;4)"fg_magenta="$(tput&nbsp;setaf&nbsp;5)"fg_cyan="$(tput&nbsp;setaf&nbsp;6)"fg_white="$(tput&nbsp;setaf&nbsp;7)"reset="$(tput&nbsp;sgr0)"用于echo&nbsp;-e&nbsp;"${fg_red}&nbsp;&nbsp;Red&nbsp;&nbsp;${fg_green}&nbsp;Bull&nbsp;${reset}"
随时随地看视频慕课网APP
我要回答