3 回答

TA貢獻2003條經驗 獲得超2個贊
基本
我編寫了一個C ++類,可用于設置輸出的前景色和背景色。此示例程序用作打印This ->word<- 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";
}
};
}
高級
您可能希望為該類添加其他功能。例如,可以添加顏色洋紅色甚至粗體樣式。為此,只需Code枚舉的另一個條目。這是一個很好的參考。

TA貢獻1810條經驗 獲得超4個贊
在您輸出任何顏色之前,您需要確保您在終端:
[ -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字符那樣使用著色。使用標準調用終端功能,為您分配特定終端支持的CORRECT顏色。
基于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}"
- 3 回答
- 0 關注
- 659 瀏覽
添加回答
舉報