C语言 从键盘检查按键的 C 库函数(在 linux 中)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20349585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C library function to check the keypress from keyboard( in linux )
提问by user3035481
Is there any C library function to check the keypress from keyboard( I am working on linux machine ).
是否有任何 C 库函数来检查键盘上的按键(我在 linux 机器上工作)。
回答by Constantin
getchar()from the Header file stdio.hreturns the next character from stdin. That's probably what you're searching for.
getchar()从头文件stdio.h返回来自标准输入的下一个字符。这可能就是你正在寻找的。
The following code will output the first char from the stdin stream:
以下代码将从标准输入流中输出第一个字符:
#include <stdio.h>
int main (int argc, char **argv){
char c = getchar();
printf("Char: %c", c);
return 0;
}
There are also other functions available to do this without blocking i.e. kbhit()and getch() in conio.h. But the header file conio.his non-standard and probably not available on your platform if you are using linux.
还有其他函数可以在不阻塞 iekbhit()和 getch() in 的情况下执行此操作conio.h。但是头文件conio.h是非标准的,如果您使用的是 linux,则可能在您的平台上不可用。
So you have 2 options:
所以你有两个选择:
1.) Using the library ncursesyou can use i.e. the function timeout()to define an timeout for the getch()function like this:
1.) 使用库ncurses,您可以使用即函数timeout()为函数定义超时,getch()如下所示:
initscr();
timeout(1000);
char c = getch();
endwin();
printf("Char: %c\n", c);
2.) Implement kbhit()by yourself without using ncurses. There is a great expanation hereto do so. You would have to measure time by yourself and looping until your timeout is reached. To measure time in C, there are plenty threads here on stackoverflow - you just have to search for it. Then your code would look like this:
2.)kbhit()自己实现,不使用 ncurses。有一个伟大的expanation这里这样做。您必须自己测量时间并循环直到达到超时。为了用 C 测量时间,stackoverflow 上有很多线程——你只需要搜索它。然后你的代码看起来像这样:
while(pastTime() < YOUR_TIMING_CONSTRAINT){
if (kbhit()){
char c = fgetc(stdin);
printf("Char: %c\n", c);
}
}
回答by niko
You can use getchar()or getc(stdin), these are standard functions in C. They echo the character to the terminal that was pressed.
您可以使用getchar()或getc(stdin),这些是 C 中的标准函数。它们将字符回显到按下的终端。
or even getch().The advantage is, it does not echo the characters pressed to the terminal. Note getch()is not a part of standard C. You could write your own function for getch()or use curses.h
甚至getch(). 优点是,它不会回显按下到终端的字符。Notegetch()不是标准 C 的一部分。您可以编写自己的函数getch()或使用curses.h

