我需要能够使终端上的某些文本更加引人注目,而我的想法是让文本着色。要么是实际的文本,要么是每个字母的矩形中的空格(想想 vi 的光标)。我认为对我的应用程序唯一重要的两个额外规范是:程序应该是发行版独立的(可以肯定的是代码只能在 BASH 下运行),并且在写入文件时不应该输出额外的字符(来自实际代码,或者在管道输出时)
我在网上搜索了一些信息,但我只能找到已弃用的 cstdlib (stdlib.h) 的信息,我需要(实际上,它更像是“想要”)使用 iostream 的功能来完成它。
大多数终端都遵循 ASCII 颜色序列。它们的工作方式是输出 ESC
,然后是 [
,然后是分号分隔的颜色值列表,然后是 m
。这些是共同的值(value)观:
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";
}