【发布时间】:2021-11-16 22:16:37
【问题描述】:
有办法改变 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(int argc, char const *argv[])
{
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;
}
我有这个我测试过的代码,但是颜色刚刚显示在 vs 代码终端上。我想知道当我编译从代码生成的二进制代码时,是否有一种方法可以在 cmd 中显示。
【问题讨论】:
-
颜色是终端功能的一部分,而不是编译后的代码。显然“vs code 终端”具有 ANSI 兼容的颜色功能,而“cmd”则没有。
-
这取决于输出被发送到的控制台。在某些终端中,这看起来就像您想要的那样。在某些情况下,它会显示为正常的无色文本。在某些情况下,它会显示为垃圾。
-
可以通过
SetConsoleMode函数更改Windows控制台模式以解释ANSI转义序列,但我不知道是否有内置或外部命令可以从CMD shell中执行此操作当前控制台,或者如果它在命令之间被 CMD shell 关闭。 -
显然,ANSI 转义序列支持是在 Windows 10 TH2 (v1511) 中添加的,并且开箱即用。见stackoverflow.com/a/35864976/5264491 和superuser.com/a/1050078
-
这能回答你的问题吗? Using colors with printf