0%

Print Ansi Color String on Terminal

有時候想要在Linux的Terminal想要印出彩色字串方便,可以有以下方法

C Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#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;
}

這方法簡單,不過麻煩的是要手動加上Color跟Reset標籤在文字前後。

C++11 Solution

突然想到可以用C++11的新特性User defined literal來簡化,可以減少不少手動置入的風險。也可以練習User defined literal的如何使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <stdio.h>
#include <string>
namespace {
#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"


#define DEFINE_COLOR_STRING(color) \
std::string operator"" _##color (const char* str) \
{ \
std::string tmp(ANSI_COLOR_##color); \
tmp += str; \
tmp += ANSI_COLOR_RESET; \
return tmp;\
}
DEFINE_COLOR_STRING(RED);
DEFINE_COLOR_STRING(GREEN);
DEFINE_COLOR_STRING(YELLOW);
DEFINE_COLOR_STRING(BLUE);
DEFINE_COLOR_STRING(MAGENTA);
DEFINE_COLOR_STRING(CYAN);
};
std::cout << 123_RED << 456_YELLOW << 789_BLUE << std::endl;

不過User Defined Literal前的字串似乎不能寫成”123 456”_RED這種形式。有點可惜

```