如何打印在彩色变量的值红色用C

如何打印在彩色变量的值红色用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() 
{ 
    char *string = "Test"; 

    printf("%s", ANSI_COLOR_RED  string  ANSI_COLOR_RESET); 

    return 0; 
} 

当这个被编译,输出的错误:

game.c:18:35: error: expected ‘)’ before ‘string’ 
printf("%s", ANSI_COLOR_RED  string  ANSI_COLOR_RESET); 

如何解决此错误?

+0

您可以连接字符串(如在答案选项3),但您可以连接一个文字与变量,因为你正在尝试去做。 –

printf ("\033[31;1m Red dragon \033[0m\n"); 

这是要做的。

另外一个更好的方法是做ANSI -way,使用宏。

printf ("%s%s%s\n", ANSI_COLOR_RED, string, ANSI_COLOR_RESET); 

另一种方式去了解这将是

printf (ANSI_COLOR_RED "%s\n" ANSI_COLOR_RESET, string); 
+1

或者更好,'printf(“%s%s%s \ n”,ANSI_COLOR_RED,string,ANSI_COLOR_RESET);' – AlexP

+0

@AlexP .:是的......更好。 – coderredoc

+0

或甚至'printf(ANSI_COLOR_RED“%s \ n”ANSI_COLOR_RESET,string);'':)' –