在调试程序时多数情况下要输出很多提示信息,通过控制输出字体的颜色的显示方式可以方便我们快速查看有用的信息,而printf()的终端转义就为我们提供了这样的手段。
我们大家知道在程序结尾加上\n就可在输出的时候换行,其实这就是个转义字符。而字体颜色和显示方式的转义字符由控制台控制(Console Conrols )是系统的显示功能与具体语言无关。
转义字符以控制字符'ESC'开头。该字符的ASCII码十进制表示为27,十六进制表示为0x1B,八进制表示为033。多数转义字符超过两个字符,故通常以'ESC'和左括号'['开头。该起始字符称为控制序列引导符(CSI,Control Sequence Intro),通常由'\033['或'\e['代替。
具体格式为:
\033[parameter1;parameter2...m 输出字符 \033[0m
\\ parameter为属性值,多个属性之间用分号隔开,与顺序无关。
\\ \033[0m表示将所有属性重设为默认值,否则会影响后续的输出。
注意:转义字符可被控制字符'CAN'(Cancel )和'SUB'(Substitute)中断
常用颜色属性值如下:
黑色 | 红色 | 绿色 | 黄色 | 蓝色 | 紫色 | 深绿色 | 白色 | |
字体颜色 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 |
背景颜色 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 |
部分ANSI控制码:
\33[0m 关闭所有属性
\33[1m 设置高亮度
\33[4m 下划线
\33[5m 闪烁
\33[7m 反显
\33[8m 消隐
\33[30m -- \33[37m 设置前景色
\33[40m -- \33[47m 设置背景色
\33[nA 光标上移n行
\33[nB 光标下移n行
\33[nC 光标右移n行
\33[nD 光标左移n行
\33[y;xH设置光标位置
\33[2J 清屏
\33[K 清除从光标到行尾的内容
\33[s 保存光标位置
\33[u 恢复光标位置
\33[?25l 隐藏光标
\33[?25h 显示光标
附实现程序:
运行环境:windows10->vmware15pro->Debian 6.3.0;
#include#include
int main(int argc, char* argv[]){ printf(" The colour test starting ---\n");printf(" Upcoming screen cleaning ---\n"); for(int i=3; i>0; i--) { sleep(1); printf(" Count down %d\n",i); sleep(1); } printf("\033[2J");printf("\033[30m This is black word \033[0m\n"); printf("\033[31m This is red word \033[0m\n"); printf("\033[32m This is green word \033[0m\n"); printf("\033[33m This is yellow word \033[0m\n"); printf("\033[34m This is blud word \033[0m\n"); printf("\033[35m This is purple word \033[0m\n"); printf("\033[36m This is dgreen word \033[0m\n"); printf("\033[37m This is white word \033[0m\n"); printf("\033[40m This is black bground \033[0m\n"); printf("\033[41m This is red bground \033[0m\n"); printf("\033[42m This is green bground \033[0m\n"); printf("\033[43m This is yellow bground \033[0m\n"); printf("\033[44m This is blud bground \033[0m\n"); printf("\033[45m This is purple bground \033[0m\n"); printf("\033[46m This is dgreen bground \033[0m\n"); printf("\033[47m This is white bground \033[0m\n"); printf("\033[43;35m This is purple word yellow bground \033[0m\n"); printf("\033[1m This is Thickening \033[0m\n"); printf("\033[3m This is Italics \033[0m\n"); printf("\033[4m This is Underline \033[0m\n"); printf("\033[5m This is Twinkle \033[0m\n"); printf("\033[7m This is Anti color \033[0m\n");/* printf("\033[nA"); printf("\033[nB"); printf("\033[nC"); printf("\033[nD"); //使光标上下右左移动n位 */ printf("\n The colour test end------\n\n");return 0;}
也可将其定义为宏写在头文件中,方便重复引用。
执行结果如下:
声明:
本文于网络整理,版权归原作者所有,如来源信息有误或侵犯权益,请联系我们删除或授权事宜。