带有 ncurses 的 C99 UTF8 字符

问题描述

我正在玩 ncurses 并且遇到了问题。我想用 Unicode 块字符 (U+2588,█) 绘制一个简单的框,但无法正确显示

enter image description here

如您所见,我想要的字符显示~H

我听从了 a similar question 的指示来到了发球台。最小工作示例:

#include <locale.h>
#include <ncurses.h>

int main() {
    setlocale(LC_ALL,""); // must be caled before initscr
    WINDOW *win = initscr();

    int w,h;
    getmaxyx(win,h,w);
    
    // should fill the left half of the 
    // terminal window with filled block characters
    int i,j;
    for (i = 0; i < h; i++) {
        for (j = 0; j < w/2; j++) {
            mvaddch(x,y,L'\u2588');
        }
    }

    refresh(); // show changes
    getch();   // wait for user input
    endwin();  // kill window
    
    return 1;
}

编译:

gcc main.c -o main -std=c99 -lncurses

minimal working example demonstration

我的 PC 语言环境是 en_US.UTF-8,我使用的是无油终端,当然是 perfectly capable of dislaying utf8:

st utf8 demonstration

这是一个非常简单的程序,我不确定这里出了什么问题。有什么建议吗?

解决方法

手册页提供了用于函数参数的 short overview of data-types

在示例中,L'\u2588' 是一个宽字符,它将存储在 wchar_t 类型中。

  • mvaddch 函数使用 chtype,这与 wchar_t 不同。
  • 对应于mvaddch的curses函数是mvadd_wch,它使用第三种类型(cchar_t)。
  • 您可以使用setcchar将该宽字符转换为cchar_t,或者
  • 您可以将该值存储在一个 wchar_t 数组中,然后将 that 传递给 mvaddwstr