C语言 c编程检查是否按下键而不停止程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13547471/
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 programming check if key pressed without stopping program
提问by Ouerghi Yassine
as you know, when using getch() in windows, the applications waits for you until you press a key,
如您所知,在 Windows 中使用 getch() 时,应用程序会等待您,直到您按下某个键,
how can i read a key without freezing the program , example :
如何在不冻结程序的情况下读取密钥,例如:
void main(){
char c;
while(1){
printf("hello\n");
if (c=getch()) {
.
.
.
}
}
thank you.
谢谢你。
回答by emil
You can use kbhit()to check if a key is pressed:
您可以使用kbhit()来检查是否按下了某个键:
#include <stdio.h>
#include <conio.h> /* getch() and kbhit() */
int
main()
{
char c;
for(;;){
printf("hello\n");
if(kbhit()){
c = getch();
printf("%c\n", c);
}
}
return 0;
}
More info here: http://www.programmingsimplified.com/c/conio.h/kbhit
回答by Harmeet
I needed similar functionality in a console application in Linux, but Linux don't provide kbhitfunction. On searching Google, I found an implementation at -
我在 Linux 的控制台应用程序中需要类似的功能,但 Linux 不提供kbhit功能。在搜索谷歌时,我发现了一个实现 -

