c - 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 中显示。
解决方案
简短的回答是肯定的。
但这与C无关。这取决于您使用的操作系统和环境,例如控制台的类型。在 Windows 下,您可以在Microsoft Docs中完整记录控制台模式。
在 Linux 下,您可以根据数字 VT 终端系列命令代码获得 90 年代的这些转义代码。这些命令在最新版本的 Windows 下也可用,例如 VT-Terminals,因此您现在可以在 Linux Windows 或 MacOS 上拥有可移植的东西。
在 Linux 下使用curses库很常见,最初来自 Unix System V,现在以ncurses的形式,也移植到 Windows,在控制屏幕和颜色方面有一些帮助
推荐阅读
- javascript - 在 React 中单击按钮时清除输入
- javascript - 在箭头函数执行期间过滤数组
- reactjs - react 说 Error: Invalid hook call when I try to use material makestyles
- sql - 使用数据库链接时在多个条件下进行内连接
- android - 保存片段状态导航组件JAVA
- python - Python Selenium - 数据不可见;没有错误
- javascript - 画布上下文上的多个填充():rgba透明颜色改变
- excel - Excel 动态数组 - 可能的错误?
- javascript - 不随页面刷新的计数器
- swiftui - SwiftUI 从 UITextField 中关闭键盘