ที่นี่เราจะเห็นฟังก์ชัน kbhit ใน C โดยพื้นฐานแล้ว kbhit คือ Keyboard Hit ฟังก์ชันนี้มีอยู่ในไฟล์ส่วนหัว conio.h ดังนั้นสำหรับการใช้สิ่งนี้ เราต้องรวมไฟล์ส่วนหัวนี้ไว้ในโค้ดของเรา
ฟังก์ชันของ kbhit() คือเมื่อกดปุ่ม จะส่งกลับค่าที่ไม่ใช่ศูนย์ มิฉะนั้นจะคืนค่าศูนย์
ตัวอย่าง
#include <stdio.h>
#include <conio.h>
main() {
char ch;
printf("Enter keys (ESC to exit)\n");
while (1) { //define infinite loop for taking keys
if (kbhit) {
ch = getch(); // Get typed character into ch
if ((int)ch == 27) //when esc button is pressed, then it will comeout from loop
break;
printf("You have entered : %c\n", ch);
}
}
} ผลลัพธ์
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 : &
หมายเหตุ: kbhit() นี้ไม่ใช่ไลบรารีมาตรฐาน ดังนั้นเราควรหลีกเลี่ยงสิ่งนี้ในโค้ดของเรา