大多数终端都遵循ASCII颜色序列。它们的工作方式是输出ESC,然后输出,[然后是分号分隔的颜色值列表,然后是m。这些是常见的值:
Special0 Reset all attributes1 Bright2 Dim4 Underscore 5 Blink7 Reverse8 HiddenForeground colors30 Black31 Red32 Green33 Yellow34 Blue35 Magenta36 Cyan37 WhiteBackground colors40 Black41 Red42 Green43 Yellow44 Blue45 Magenta46 Cyan47 White
因此,输出
" 33[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 = " 33["; 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";}


