您要输入的字符需要程序设置语言环境。如manual中所述:
Initialization
The library uses the locale which the calling program has
initialized. That is normally done with setlocale:
setlocale(LC_ALL, "");
If the locale is not initialized, the library assumes that
characters are printable as in ISO-8859-1, to work with
certain legacy programs. You should initialize the locale
and not rely on specific details of the library when the
locale has not been setup.
除此之外,您的语言环境很可能使用 UTF-8。要使用 UTF-8,您应该编译并链接到 ncursesw 库。
此外,getch 函数仅返回单字节编码的值,例如 ISO-8859-1,有些人将其与 Windows cp1252 混淆,因此返回“扩展 ASCII”(这说明了两个谬误不取消)。 UTF-8 是一种多字节编码。如果你使用getch 读取那个,你会得到字符的第一个字节。
相反,要读取 UTF-8,您应该使用 get_wch(除非您想自己解码 UTF-8)。这是一个修改后的程序:
#include <ncurses.h>
#include <locale.h>
#include <wchar.h>
int
main(void)
{
wint_t value;
setlocale(LC_ALL, "");
initscr();
get_wch(&value);
mvprintw(0, 0, "letter: %#x.", value);
refresh();
getch();
endwin();
return 0;
}
我将结果打印为数字,因为printw 不知道 Unicode 值。 printw 使用与 printf 相同的 C 运行时支持,因此您可以直接打印该值。例如,我看到POSIX printf 有一个格式化选项来处理wint_t:
c
int 参数应转换为unsigned char,并写入结果字节。
如果存在 l (ell) 限定符,则 wint_t 参数应按照 ls 转换规范进行转换没有精度且参数指向wchar_t 类型的双元素数组,其中第一个元素包含 ls 转换规范的wint_t 参数,第二个元素包含一个空宽字符。
由于 ncurses 可在许多平台上运行,并非所有平台都支持该功能。但您可以假设它适用于 GNU C 库:大多数发行版通常都提供可行的语言环境配置。
这样做,例子更有趣:
#include <ncurses.h>
#include <locale.h>
#include <wchar.h>
int
main(void)
{
wint_t value;
setlocale(LC_ALL, "");
initscr();
get_wch(&value);
mvprintw(0, 0, "letter: %#x (%lc).", value, value);
refresh();
getch();
endwin();
return 0;
}