您的位置:首页 > 编程语言 > C语言/C++

用C语言在终端打印彩色字符串

2015-12-10 12:37 603 查看
看别人的开源项目的时候发现,原来在终端可以打印带颜色的字符串的。。还蛮有意思的,只需要在待打印的字符串前面和后面分别加一串修饰字符就行了。

下面是C语言的一个例子:

#include <stdio.h>

#define ANSI_COLOR_RED     "\x1b[31m"
#define ANSI_COLOR_GREEN   "\x1b[32m"
#define ANSI_COLOR_YELLOW  "\x1b[33m"
#define ANSI_COLOR_BLUE    "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN    "\x1b[36m"
#define ANSI_COLOR_RESET   "\x1b[0m"

int main() {

printf(ANSI_COLOR_RED     "This text is RED!"     ANSI_COLOR_RESET "\n");
printf(ANSI_COLOR_GREEN   "This text is GREEN!"   ANSI_COLOR_RESET "\n");
printf(ANSI_COLOR_YELLOW  "This text is YELLOW!"  ANSI_COLOR_RESET "\n");
printf(ANSI_COLOR_BLUE    "This text is BLUE!"    ANSI_COLOR_RESET "\n");
printf(ANSI_COLOR_MAGENTA "This text is MAGENTA!" ANSI_COLOR_RESET "\n");
printf(ANSI_COLOR_CYAN    "This text is CYAN!"    ANSI_COLOR_RESET "\n");

return 0;
}


在终端的运行结果如下图所示:



其它更多的颜色可以参考:ANSI escape code

对于其他的编程语言也是一样的。

参考链接

1.http://stackoverflow.com/questions/3219393/stdlib-and-colored-output-in-c
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: