ANSI escape codes not displaying correctly

放肆的年华 提交于 2021-02-05 09:14:05

问题


I have the following defines:

#define ANSI_COLOR_RED     "\e[31m"
#define ANSI_COLOR_GREEN   "\e[32m"
#define ANSI_COLOR_YELLOW  "\e[33m"
#define ANSI_COLOR_BLUE    "\e[34m"
#define ANSI_COLOR_MAGENTA "\e[35m"
#define ANSI_COLOR_CYAN    "\e[36m"
#define ANSI_COLOR_RESET   "\e[0m"

I then use these like so:

char *getStatusColour(eTaskState state) {
    switch (state) {
        case eRunning:
            return ANSI_COLOR_GREEN;
            break;
        case eReady:
            return ANSI_COLOR_YELLOW;
            break;
        case eBlocked:
            return ANSI_COLOR_RED;
            break;
        case eSuspended:
            return ANSI_COLOR_BLUE;
            break;
        case eDeleted:
            return ANSI_COLOR_RESET;
            break;
    }

    return ANSI_COLOR_RESET;
}

printf("%s TEST %s\n", getStatusColour(eRunning), ANSI_COLOR_RESET);

The terminal output, however, does not work (IE: No colours and where the colour "should" be, is an unknown character (IE: Something not displayable).

Any ideas why this would not be working?

EDIT

It should be noted I get some colours printing when I change to:

#define ANSI_COLOR_GREEN \e[32m\\]

But the text is truncated, and I'm not sure what the \\] does.


回答1:


Notice that \e is not a standard escape code and may thus fail (behaviour is undefined!):

% gcc ansi.c -pedantic
ansi.c: In function ‘main’:
ansi.c:4:12: warning: non-ISO-standard escape sequence, '\e'
     printf("\e[1;32mfoobar");

Use \033 or \x1B instead.



来源:https://stackoverflow.com/questions/37203782/ansi-escape-codes-not-displaying-correctly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!