大多数终端都遵循 ASCII 颜色序列。它们的工作方式是输出ESC,然后是[,然后是分号分隔的颜色值列表,然后是m。这些是常见的值:
Special
0 Reset all attributes
1 Bright
2 Dim
4 Underscore
5 Blink
7 Reverse
8 Hidden
Foreground colors
30 Black
31 Red
32 Green
33 Yellow
34 Blue
35 Magenta
36 Cyan
37 White
Background colors
40 Black
41 Red
42 Green
43 Yellow
44 Blue
45 Magenta
46 Cyan
47 White
所以输出"\033[31;47m" 应该使终端正面(文本)颜色为红色,背景颜色为白色。
你可以用 C++ 形式很好地包装它:
enum Color {
NONE = 0,
BLACK, RED, GREEN,
YELLOW, BLUE, MAGENTA,
CYAN, WHITE
}
std::string set_color(Color foreground = 0, Color background = 0) {
char num_s[3];
std::string s = "\033[";
if (!foreground && ! background) s += "0"; // reset colors if no params
if (foreground) {
itoa(29 + foreground, num_s, 10);
s += num_s;
if (background) s += ";";
}
if (background) {
itoa(39 + background, num_s, 10);
s += num_s;
}
return s + "m";
}