如何向Linux终端输出彩色文本? [英] How do I output coloured text to a Linux terminal?

查看:163
本文介绍了如何向Linux终端输出彩色文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在支持此功能的Linux终端上打印彩色字符?

How do I print coloured characters to a Linux terminal that supports it?

如何判断终端是否支持彩色代码?

How do I tell whether the terminal supports colour codes?

我为这个程序使用C ++。

I'm using C++ for this program.

推荐答案

您需要输出 ANSI颜色代码。注意,并非所有终端都支持此功能;如果不支持颜色序列,则会显示垃圾。

You need to output ANSI colour codes. Note that not all terminals support this; if colour sequences are not supported, garbage will show up.

示例:

 cout << "\033[1;31mbold red text\033[0m\n";

这里, \033 其后是 [,然后是由; 分隔的一个或两个数字,最后是字母 m 。请参阅维基百科上的表格了解数字的含义。

Here, \033 is the ESC character, ASCII 27. It is followed by [, then one or two numbers separated by ;, and finally the letter m. See the table on Wikipedia for the meaning of the numbers.

编辑:要确定您的终端是否支持颜色序列,请读取 TERM 环境变量。它应该指定使用的特定终端类型(例如 vt100 gnome-terminal xterm 屏幕,...)。然后在 terminfo数据库中查找;请检查颜色能力。

To determine whether your terminal supports colour sequences, read the value of the TERM environment variable. It should specify the particular terminal type used (e.g. vt100, gnome-terminal, xterm, screen, ...). Then look that up in the terminfo database; check the colors capability.

这篇关于如何向Linux终端输出彩色文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆