2017-11-11 148 views
0

我想用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),但您可以連接一個文字與變量,因爲你正在嘗試去做。 –

回答

4
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);'':)' –