kbhit()的三个测试

 1 #include <stdio.h>
 2 #include<conio.h>
 3 #include<stdlib.h>
 4 int main()
 5 {
 6     int i=0;
 7     system("cls");
 8     while(!kbhit())
 9     {
10         system("cls");
11         printf("%05d",i++);
12     }
13     system("cls");
14     printf("End.");
15     getchar();
16     return 0;
17 }
 1 /* KBHIT.C: This program loops until the user * presses a key. If _kbhit returns nonzero,
 2 a * keystroke is waiting in the buffer. The program * can call _getch or _getche to get the keystroke. */
 3 #include <conio.h>
 4 #include <stdio.h>
 5 void main( void )
 6 {       /* Display message until key is pressed. */      
 7     while( !_kbhit() )          
 8         _cputs( "Hit me!! " );//注意与puts()的区别
 9     printf( "/nKey struck was '%c'/n", _getch() );      
10     _getch();
11 }
 1 #include<stdio.h>
 2 #include<conio.h>
 3 int main() {
 4     char c;
 5     while(1) {
 6             if(kbhit()){                  /*-1的时候显示并用getchar()读一个字符再显示,若0则直接显示*/
 7                     printf("%d",kbhit());
 8                     printf("%c",getchar());
 9                }
10                 else
11                     printf("%d",kbhit() );
12 
13 
14     }
15 }
16 
17 /*
18 ----------------------------1: kbhit()有键按下返回-1,无键按下返回0;
19 如果注释起作用的话
20 运行1:  
21 循环输出0 
22 直到有键按下
23 getchar()等待回车
24 循环输出-1 
25 再按键无改观,死循环输出-1.
26                          ---如果键盘缓冲区中无剩余字符getchar()也表现为阻塞,并且不按回车不开始读入字符.
27 以下注释不起作用  
28 运行2:
29 循环输出0 
30 输入f 回车 
31 循环输出0 
32 第二次按下键
33 在你输入的字符前屏幕换行,换行之前-1
34                            ---屏幕换行说明一次getchar()只从键盘缓冲区消耗一个字符,这个换行符是上次getchar()留下的回车键.
35 
36 运行3:
37 循环输出0 
38 输入多个字符,回车
39 循环输出0 
40 第二次按键
41 显示多个-1之后,屏幕换行,显示输入的字符000000
42                           ---为什么会显示多个负1,这是因为kbhit的状态一直未改变,为什么没改变,见下分析
43 
44 
45 键盘输入产生硬件中断,程序处理,提交给操作系统,操作系统通知相应程序并等待用户程序取走,kbhit()检测操作系统有没有键盘输入数据要递交过来,若有,其返回-1,若没有,返回0.
46 直到当程序从操作系统处读取到数据时(getchar,scanf等)再调用kbhit()才会返回0(操作系统与程序的接口处的键盘数据缓冲区清空).
47 程序读过数据之后将之放到程序内部的数据段的键盘缓冲区(上面两个注释是指程序内部数据段)
48 
49 getchar()会从程序数据段的键盘缓冲区来读取一个字符(读取的同时删除)如果其内容为空的话,刚检测操作系统处有无数据,如果有的话,
50 读取一行(找回车)到程序数据段后再重新读取一个字符,如果没有数据,或者有数据但没有回车符,则在此阻塞,等待
51 
52 ------------------------------2: 因此只说kbhit()有键按下返回-1,无键按下返回0;不太正确,
53                                          得加上句:如果程序不从操作系统读取键盘数据前,kbhit()将保持-1.
54 
55 kbhit()不起作用的键:ctrl shift caps_lock print_Screen num_lock,INSERT键可以,笔记本上右边alt键和ctrl键之间的也即是鼠标右键
56 */

 

posted @ 2013-08-13 01:23  herizai007  阅读(1229)  评论(0编辑  收藏  举报