使用 curses.h 从键盘获取字符

getting a char from keyboard using curses.h

我正在尝试使用 curses.h 从键盘获取一个字符。 这是我的来源 (get_char_example.c):

#include <curses.h>
#include <stdio.h>

int main(void)
{
    char ch;

    printf("Enter a character: ");
    ch = getch();
    printf("\nIts ASCII code is %d\n", ch);

    return 0;
}

我使用以下命令编译:

gcc get_char_example.c -o get_char_example

我收到以下错误:

/tmp/ccjaXwRU.o: 在函数`main'中:

get_char_example.c:(.text+0x1c): undefined reference to `stdscr'
get_char_example.c:(.text+0x24): undefined reference to `wgetch'
collect2: error: ld returned 1 exit status

使用:gcc (GCC) 7.2.0 拱门 Linux 4.13.9-1-拱门

提前致谢!

这是一个链接器错误(请参阅 this, nearly a duplicate). ncurses is generally known to pkg-config(需要时会提供更多依赖项),因此请尝试编译:

 gcc -Wall -Wextra -g \
    $(pkg-config --cflags ncurses) \
    get_char_example.c \
    $(pkg-config --libs ncurses)

您想要 Invoke GCC with all warnings and debug info; you would use GDB,也许在 emacsddd 下,用于调试。

更好的是,使用一些 build automation tool (like make or ninja). With GNU make take inspiration from this to write your Makefile(其中 tab-s 很重要)。

在我的 Debian Sid 上,pkg-config --cflags ncurses 给出 -D_GNU_SOURCE -D_DEFAULT_SOURCEpkg-config --libs ncurses 给出 -lncurses -ltinfo,所以简单地与 -lncurses 链接是 不是 足够了(这就是为什么 this 在 2017 年 11 月的今天并不完全重复;几年前简单地链接 -lncurses 就足够了,今天却不是)。

使用pkg-config --list-all查找pkg-config已知的所有包和库;在开发 您的 库时,请考虑为其提供一些 .pc 文件。

顺便说一句,您的程序应该首先使用 initscr 进行初始化并使用 printw;阅读Ncurses-programming-HowTo即使有点老

另请注意,在 21st 世纪使用 ASCII 已过时。 程序和计算机使用UTF-8 everywhere, and this has profound consequences you should be aware of (since an UTF-8 character can span several bytes). My French keyboard has keys for ², §, and é (even with American keyboards your could paste them) and none of these are in ASCII. Consider also using some UTF-8 library like libunistring