kbhit()

除了標準函式庫之外,C編譯器還會附帶一些非標準函式庫,像是這邊要介紹的conio就是非標準I/O的函式庫,使用了非標準函式庫有時雖然方便,但在不同平台上移植時,就會有相容性問題。

這邊介紹一下getche()、getch()與kohit()三個標準輸入。

當您使用標準輸入函式getchar()時,必須按下Enter鍵,才會取得第一個輸入的字元,其它未取得的字元則留在緩衝區中,等待下一次getchar()或scanf()。

無論是使用getche()或getch(),執行到該行時,程式會暫停並等待使用者的輸入。如果使用getche(),則每按下一個字元就馬上取得,不用等按下Enter鍵,使用getche(),使用者在輸入時也會在螢幕上顯示所輸入的字元,但使用getch()則不會顯示輸入的字元。

執行kbhit()時,會直接檢查當時使用者是否有按下任何按鍵,如果有的話傳回非零值,沒有按下任何鍵的話則傳回0,但不會暫停程式等待使用者輸入。

使用getche()、getch()或kbhit()時,必須包括conio.h這個標頭檔:

#include

EX
#include int main(){
while(true) {
// Poll the console without blocing, return true if there is
// a keystroke waiting in the buffer.
if (kbhit()) {
if (getchar() == 'q')
break;
}
// Do something usefull
// ...
}
return 0;
}


可惜 kbhit() 不是標準 C 裡的成員,在若干平台上我們得自行實踐.
以下為原始碼

#include
int kbhit(void){
struct timeval tv; fd_set read_fd;

/* Do not wait at all, not even a microsecond */
tv.tv_sec=0;
tv.tv_usec=0;

/* Must be done first to initialize read_fd */
FD_ZERO(&read_fd);

/* Makes select() ask if input is ready: 0 is the file descriptor for stdin */
FD_SET(0, &read_fd);

/* The first parameter is the number of the largest file descriptor to check + 1. */
if (select(1, &read_fd, NULL /*No writes*/, NULL /*No exceptions*/, &tv) == -1)
return 0; /* An error occured */

/* read_fd now holds a bit map of files that are readable.
* We test the entry for the standard input (file 0). */
if (FD_ISSET(0, &read_fd)) /* Character pending on stdin */
return 1;

/* no characters were pending */
return 0;
}


arrow
arrow
    全站熱搜

    BB 發表在 痞客邦 留言(0) 人氣()