1. 程式人生 > >C++ kbhit()函式和 getch()函式配套解讀

C++ kbhit()函式和 getch()函式配套解讀

1. 功能及返回值

  • kbhit()函式檢測鍵盤是否有鍵按下,如果有鍵按下,則返回對應鍵值(ASCII碼值);否則返回零,kbhit不等待鍵盤按鍵,無論有無按鍵都會立即返回 
  • getch()函式從鍵盤讀入一個字元,返回字元的 ASCII 碼值
#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
	/* Display message until key is pressed */
	while (!kbhit())
	{
		cout << "Hit me!   ";
	}

	cout << "/nkey struck was " << getch() << endl;
		
	
	return 0;
}

沒有鍵盤按下,那麼 while 迴圈一直執行,當有鍵盤按下,那麼就會跳出 while 迴圈,然後輸出按下的 ASCII 碼