C中kbhit()和getch()

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();
}

 C_kbhit()和getch()函数的使用

结合一起使用:

#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);
	}
}

运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值