C/C++檢測鍵盤輸入,可以用kbhit()函數和或getch()函數。
kbhit()的用法
頭文件包括“conio.h”。
程序執行到kbhit()時,等待輸入,但是不會停止而是繼續運行,有輸入時kbhit()才就返回一個非零值,否則返回0。下面是一個例子。
#include <iostream> #include "conio.h" using std::cout; int main() { int times = 5; cout<<"Press any key:\n"; while(times) { if(!kbhit()) { cout<<"No input now!\n"; } times--; } return 0; }
輸出:
程序執行到 if(!kbhit()) 時,因為當前沒有輸入,所以會連續打印“Now input now!”五次結束。中間的時間根本來不及打斷。
如果寫個下面的例子,更加直觀。
#include <iostream> #include "conio.h" using std::cout; int main() { while(!kbhit()) { cout<<"Now input now!\n"; } return 0; }
程序會不斷地打印“Now input now!”,直到隨便按下一個按鍵,程序跳出循環,執行結束。
getch()的用法
頭文件包括“conio.h”。
程序執行到getch(),會保持等待狀態,請求用戶輸入。按下一次按鍵后,讀取一個字符,然后程序繼續執行。這個字符可以賦值給其它變量。
舉個例子:
#include <iostream> #include "conio.h" using std::cout; int main() { int n; char c; cout<<"Press any key:\n"; getch(); cout<<"You pressed a key.\n"; cout<<"Press another key:\n"; c = getch(); cout<<"You pressed "<<c<<"\n"; cout<<"Press another key again:\n"; n = getch(); cout<<"You pressed "<<n<<"\n"; //ASCII return 0; }
三次輸入,按下的都是“a”。最后輸出:
結合以上特點,下面寫個小游戲練習鍵盤輸入檢測。
練習
程序運行后,會顯示一個密碼盤,有0-9總共10個數字,並顯示一個能由用戶操控的光標(*),開始時居中,形式如下。
按下a鍵和d鍵控制光標分別向左和向右移動(稱為key)。密碼自由設定,有先后順序。在下面的例程中,用戶需要先向左轉到1,再向右轉到8,依次打開兩道鎖。每次打開鎖后,會輸出一行提示。
效果:
兩道鎖都打開后,按下任意按鍵退出。
代碼中用了system(“cls”)來清屏,用了Sleep()來讓系統等待特定的時間。(引用頭文件“windows.h”)
#include <iostream> #include "windows.h" //for system("cls") and Sleep() #include "conio.h" //for getch() #include <string> //for string using std::cout; using std::string; //此處定義光標的圖案和密碼位置 const char key = '*'; const int pw1 = 2; const int pw2 = 16; //顯示密碼鎖的界面 void show() { string numbers = "0 1 2 3 4 5 6 7 8 9\n"; string lines = "| | | | | | | | | |\n"; cout<<numbers; cout<<lines; } //輸出空格 void space(int i) { char space = '\0'; for(;i>0;i--) { cout<<space; } } //核對密碼 bool check_key_1(int k) { return k == pw1; } bool check_key_2(int k) { return k == pw2; } void move_key() { int place = 9; //空格數,定位用 char p; //用戶的鍵盤輸入 int counts = 0; //解鎖次數統計 show(); //顯示界面 space(place); cout<<key; //定位並顯示光標 p = getch(); //獲取鍵盤輸入 int flag = 1; //用於保持循環的標志 while(flag) { system("cls"); //清屏刷新 show(); if( p == 'a') { place--; //光標左移一格 space(place); cout<<key<<"\n"; } else if( p == 'd') { place++; //光標右移一格 space(place); cout<<key<<"\n"; } else { break; //按下的不是a和d就退出 }; switch(counts) { case 0: { if(check_key_1(place)) { cout<<"First lock Unlocked!\n"; Sleep(1000); //等待一秒 counts ++; } else{} break; } case 1: { if(check_key_2(place)) { cout<<"Second lock Unlocked!\n"; Sleep(1000); counts ++; } else{} break; } default: { cout<<"All locks have been unlocked.\n"; cout<<"Press any key to continue..."; Sleep(1000); flag = 0; break; } } p = getch(); //獲取下一次鍵盤輸入 } } int main() { move_key(); return 0; }