如何使用C以红色打印变量的值

McG*_*izz 1 c printf

我想使用 C 打印彩色文本。这是我的代码:

\n\n
#include <stdio.h>\n\n#define ANSI_COLOR_RED     "\\x1b[31m"\n#define ANSI_COLOR_GREEN   "\\x1b[32m"\n#define ANSI_COLOR_YELLOW  "\\x1b[33m"\n#define ANSI_COLOR_BLUE    "\\x1b[34m"\n#define ANSI_COLOR_MAGENTA "\\x1b[35m"\n#define ANSI_COLOR_CYAN    "\\x1b[36m"\n#define ANSI_COLOR_RESET   "\\x1b[0m"\n\nint main()\n{\n  char *string = "Test";\n\n  printf("%s", ANSI_COLOR_RED     string     ANSI_COLOR_RESET);\n\n  return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

编译时会输出错误:

\n\n
game.c:18:35: error: expected \xe2\x80\x98)\xe2\x80\x99 before \xe2\x80\x98string\xe2\x80\x99\nprintf("%s", ANSI_COLOR_RED     string     ANSI_COLOR_RESET);\n
Run Code Online (Sandbox Code Playgroud)\n\n

我该如何修复这个错误?

\n

use*_*738 5

printf ("\033[31;1m Red dragon \033[0m\n");
Run Code Online (Sandbox Code Playgroud)

这就是做法。

另外一个更好的方法是ANSI使用宏来做到这一点。

printf ("%s%s%s\n", ANSI_COLOR_RED, string, ANSI_COLOR_RESET);
Run Code Online (Sandbox Code Playgroud)

另一种方法是

printf (ANSI_COLOR_RED "%s\n" ANSI_COLOR_RESET, string);
Run Code Online (Sandbox Code Playgroud)