你需要输出ANSI colour codes.请注意,并非所有终端都支持此功能;如果不支持 colored颜色 序列,则会出现垃圾.
例子:
cout << "\033[1;31mbold red text\033[0m\n";
这里,\033
是ESC字符,ASCII 27.它的后面是[
,然后是以;
分隔的零或多个数字,最后是字母m
.这些数字描述了从那时起要切换到的 colored颜色 和格式.
前景色和背景色的代码如下:
foreground background
black 30 40
red 31 41
green 32 42
yellow 33 43
blue 34 44
magenta 35 45
cyan 36 46
white 37 47
此外,您还可以使用以下功能:
reset 0 (everything back to normal)
bold/bright 1 (often a brighter shade of the same colour)
underline 4
inverse 7 (swap foreground and background colours)
bold/bright off 21
underline off 24
inverse off 27
其他支持较少的代码请参见table on Wikipedia.
要确定终端是否支持 colored颜色 序列,请读取TERM
环境变量的值.它应该指定使用的特定端子类型(例如vt100
、gnome-terminal
、xterm
、screen
等).然后在terminfo database中查找;判断colors
的性能.