如何在Linux中使用c的getch函数?
问题描述:
我已经在Linux mint中安装了ncurses
库,但我仍然不能在c中使用getch
函数。我正在使用Linux mint 18.2。如何在Linux中使用c的getch函数?
这里是我的程序:
#include <stdio.h>
#include <curses.h>
int main() {
char k;
printf("how are you");
k = getch();
printf("%c",k);
}
这里是输出:
[email protected]$ gcc-7 test.c -lcurses
[email protected]$ ./a.out
how are you�[email protected]$
但这并没有等我按任意键并迅速终止。我不想为Linux安装conio.h
。我如何在Linux中使用getch
和getche
函数?请不要告诉我做我自己的功能。我仍然是一个noob。或者必须有替代品。
答
这里有一个“修正版”,解释什么是错的评论:
#include <curses.h>
#include <stdio.h>
int main(void)
{
// use the correct type, see https://linux.die.net/man/3/getch
int k;
// init curses:
initscr();
// in curses, you have to use curses functions for all terminal I/O
addstr("How are you?");
k = getch();
// end curses:
endwin();
printf("You entered %c\n", k);
return 0;
}
这仍然是不好的代码,你至少应该检查是否从getch()
得到了有效的字符。
重要的是要注意getch()
不是“C的函数”。它是curses
的一部分,它是用于控制台/终端控制的众所周知的与平台无关的API,其实现例如* nix系统(ncurses
)和Windows(pdcurses
)。它是而不是语言C的一部分。
'getch()'只有在初始化curses后定义了行为。谷歌至少在'initscr()'和'endwin()'。 –
顺便说一句,你不能混合'stdio'函数和'curses'函数。 –
更重要的是:为什么?你想达到什么目的?从目前的问题陈述来看,它看起来并不像你需要任何东西的ncurses。所以? –