📜  kbhit用C语言

📅  最后修改于: 2021-05-25 19:49:34             🧑  作者: Mango

kbhit()存在于conio.h中,用于确定是否已按下某个键。要在程序中使用kbhit函数,应包括头文件“ conio.h”。如果按下了某个键,则它返回一个非零值,否则返回零。

// C++ program to demonstrate use of kbhit()
#include 
#include 
  
int main()
{
    while (!kbhit())
        printf("Press a key\n");
  
    return 0;
}

输出:

"Press a key" will keep printing on the 
console until the user presses a key on the keyboard.

注意: kbhit()不是标准的库函数,应避免使用。

程序使用kbhit来获取按下的键

// C++ program to fetch key pressed using
// kbhit()
#include 
#include 
using namespace std;
int main()
{
    char ch;
    while (1) {
  
        if ( kbhit() ) {
  
            // Stores the pressed key in ch
            ch = getch();
  
            // Terminates the loop
            // when escape is pressed
            if (int(ch) == 27)
                break;
  
            cout << "\nKey pressed= " << ch;
        }
    }
    return 0;
}

输出:

Prints all the keys that will be pressed on
 the keyboard until the user presses Escape key
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。