首页 > 解决方案 > C 处的颜色输出

问题描述

有办法改变 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 中显示。

标签: cwindowsoutput

解决方案


简短的回答是肯定的。

但这与C无关。这取决于您使用的操作系统和环境,例如控制台的类型。在 Windows 下,您可以在Microsoft Docs中完整记录控制台模式。

在 Linux 下,您可以根据数字 VT 终端系列命令代码获得 90 年代的这些转义代码。这些命令在最新版本的 Windows 下也可用,例如 VT-Terminals,因此您现在可以在 Linux Windows 或 MacOS 上拥有可移植的东西。

在 Linux 下使用curses库很常见,最初来自 Unix System V,现在以ncurses的形式,也移植到 Windows,在控制屏幕和颜色方面有一些帮助


推荐阅读