如何在Linux中使用c的`getch`function?
我在Linux mint中安装了ncurses
库,但我仍然不能在c中使用getch
函数。 我正在使用Linux mint 18.2。
这是我的计划:
#include #include int main() { char k; printf("how are you"); k = getch(); printf("%c",k); }
这是输出:
ram@ram$ gcc-7 test.c -lcurses ram@ram$ ./a.out how are you ram@ram$
它不会等我按任何键并快速终止。 我不想为Linux安装conio.h
。 如何在Linux中使用getch
和getche
函数? 请不要告诉我自己的function。 我还是个菜鸟。 或者必须有替代品。
这是一个“更正”的版本,解释了评论中的错误:
#include #include 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
的一部分, curses
是一个众所周知的独立于控制台/终端控制的API,具有例如* nix系统( ncurses
)和Windows( pdcurses
)的实现。 它不是 C语言的一部分。