纯颜色着色不同于文本+颜色着色

Color-Only Coloring Differs From Text+Color-Coloring

如果我使用 chtype 打印一个字符,字符的 ncurses 容器对象,只指定一种颜色,如 COLOR_PAIR(SOME_PAIR),我得到两个颜色字符。使用 ' ' | COLOR_PAIR(SOME_PAIR),即与一个字符进行 OR-ing,正如我预期的那样,我只得到一个。

自己尝试(使用 -lncurses 构建):

#include <ncurses.h>

#define RED 1

int main(void)
{
        initscr();
        start_color();
        curs_set(0);
        init_pair(RED, COLOR_RED, COLOR_RED);

        printw("Multiple: ");
        addch(COLOR_PAIR(RED));

        printw("\t\tSingle: ");
        addch(' ' | COLOR_PAIR(RED));

        getch();
        endwin();
}

我觉得是这样的:

那里发生了什么事? addch 怎么可能 操纵多个字符?

一个chtype包含字符和属性数据。将 chtype 设置为 COLOR_PAIR(COLOR_RED),您设置的是属性数据,而不是字符数据,有效地将字符数据初始化为 0

在ASCII字符集中,字符编码0对应的是NULL字符,通常用于C语言中的字符串终止

现在,意识到它是一个不可打印的字符,因此在文本表示中用 两个 个字符表示:^@.

addch 和朋友们在比您在终端中获得的单纯字段更高的抽象级别上进行操作,它们对字符进行操作,包括不可打印的字符。

来自man curs_addch

If ch is any [non-whitespace] control character, it is drawn in ^X notation. Calling winch after adding a control character does not return the character itself, but instead returns the ^-representation of the control character.

由于 ncurses 看到 COLOR_PAIR(RED) 包含字符代码 0,ncurses 将其解释为不可打印字符并相应地打印它,一个 字符在 两个 字段中。