C语言中kbhit()函数(conio.h):检查当前是否有键盘输入,若有则返回一个非0值,否则返回0。
getch()函数,不需要回车就可以得到输入的控制字符;
一般kbhit()和getch() 搭配使用!
1、应用举例:
#include<stdio.h>
#include<conio.h>
int main()
{
int a;
a = _kbhit();
printf("%d\n",a);
return 0;
}
运行结果:
2、下面是一个实例,用户每按一次任意按键,屏幕都会打印一句:"The user presses a key.",下面是程序源代码:
#include<stdio.h>
#include<conio.h>
int main()
{
while (1) {
if (_kbhit()) {
printf("The user presses a key.\n");
_getch();
}
}
return 0;
}
运行结果:
3、用户按任意键,退出程序:
#include <graphics.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
void main()
{
srand((unsigned)time(NULL));
initgraph(640, 480);
int x, y, c;
while (!kbhit())
{
x = rand() % 640;
y = rand() % 480;
c = RGB(rand() % 256, rand() % 256, rand() % 256);
putpixel(x, y, c);
//Sleep(10);
}
closegraph();
}
结合一起使用:
#include <graphics.h>
#include <stdio.h>
#include <conio.h>
void main()
{
char c = 0;
while (c != 27)
{
if (kbhit())
c = getch();
else
c = '.';
printf("%c", c);
Sleep(100);
}
}
运行结果: