Ở đây ta sẽ xem chức năng kbhit trong C. kbhit là viết tắt của Keyboard Hit. Hàm này nằm trong header conio.h. Để dùng, phải include header này.
Chức năng của kbhit(): khi một phím được nhấn, trả về giá trị khác 0, ngược lại trả về 0.
Ví dụ
#include <stdio.h>
#include <conio.h>
int main() {
char ch;
printf("Enter keys (ESC to exit)\n");
while (1) { // vòng lặp vô tận để nhận phím
if (kbhit()) {
ch = getch(); // lấy ký tự gõ vào ch
if ((int)ch == 27) // khi nhấn ESC, thoát vòng lặp
break;
printf("You have entered : %c\n", ch);
}
}
return 0;
}
Kết quả
Enter keys (ESC to exit) You have entered : i You have entered : t You have entered : D You have entered : w You have entered : 5 You have entered : / You have entered : * You have entered : + You have entered : You have entered : o You have entered : You have entered : &
Lưu ý: kbhit() không phải thư viện chuẩn. Nên tránh dùng trong mã sản xuất.