kbhit 用法

1.源自 头文件<conio.h>

 

2. 原型:extern int kbhit(void);
  
   用法:#include <stdio.h>
  
   功能:检测按键
  
   说明:检测键盘是否有键按下。
         如果有键按下,则返回对应键值;否则返回零。
         kbhit不等待键盘按键。无论有无按键都会立即返回。
  
   举例:

       // kbhit.c
      
       #include <stdio.h>

       main()
       {
         int i=0;
        
         clrscr();
        
         while(!kbhit())
         {
           clrscr();
           printf("%05d",i++);
         }
        
         clrscr();
         printf("End.");
        
         getchar();
         return 0;
       }
      

3.kbhit()检测键盘是否有键按下,并工作在非阻塞模式下(即不等待状态,如果没有键按下,函数立即返回),如果有键按下,函数返回按键的ACSII码,

例子(来源MSDN):

/* KBHIT.C: This program loops until the user
 * presses a key. If _kbhit returns nonzero, a
 * keystroke is waiting in the buffer. The program
 * can call _getch or _getche to get the keystroke.
 */

#include <conio.h>
#include <stdio.h>

void main( void )
{
       /* Display message until key is pressed. */
       while( !_kbhit() )
          _cputs( "Hit me!! " );

       /* Use _getch to throw key away. */
       printf( "/nKey struck was '%c'/n", _getch() );
       _getch();
}

Output

Hit me!! Hit me!! Hit me!! Hit me!! Hit me!! Hit me!! Hit me!!
Key struck was 'q' 

利用此函数可实现在程序运行时按任意键继续的以功能,非常好用

如果程序是循环式的,可在循环程序中加入

while(!kbhit())

{

            char c;

             cout<<"按任意键继续程序执行,按q按退出程序";

            cin>>c;

            if(c=='q')

                 return 1;

}

如果程序不是循环时的,而是非常长的一个程序串,就要通过多线程来实现,另外创建一个线程,在新线程中使用kbhit()函数,然后调用API函数SuspendThread 暂停主线程的运行就可以了


 
  • 6
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
01-13 2652

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值