标准c语言的键盘检测只有按了回车才返回,如果要用一个while循环检测就不好使了,kbhit好像是windows的,linux下好像只有模拟,这里从一个老外网站拷贝的,貌似国人也有,与大家分享下了:
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
int kbhit(void)
{
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if(ch != EOF) {
ungetc(ch, stdin);
return 1;
}
return 0;
}
int main(void)
{
while(!kbhit()) puts("Press a key!");
printf("You pressed '%c'!/n", getchar());
return 0;
}
输出:
itsme@dreams:~/C$ ./kbhit
Press a key!
Press a key!
Press a key!
Press a key! . . .
Press a key!
Press a key!
Press a key!
Press a key!
Press a key!
You pressed 'r'!
itsme@dreams:~/C$
itsme@dreams:~/C$ ./kbhit Press a key! Press a key! Press a key! Press a key! . . . Press a key! Press a key! Press a key! Press a key! Press a key! You pressed 'r'! itsme@dreams:~/C$