[英]Why does _kbhit() only work once in a C program?
我只是寫了這個小程序,應該在打印每行之前等待用戶鍵入內容,但是它僅適用於第一個_kbhit(),之后不再等待。 為什么?
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main(void)
{
printf("Canada\n");
while ( _kbhit() == 0 );
printf("is\n");
while ( _kbhit() == 0 );
printf("great!");
while ( _kbhit() == 0 );
return 0;
}
函數參考中沒有信息表明_kbhit()在程序中只能運行一次。
盡管在該文檔頁面中沒有明確說明,但您必須使用擊鍵(使用getch
或getche
),否則_kbhit
仍然會看到它。 在while循環之后的下一個循環之前調用_getch
:
while(_kbhit() == 0);
_getch();
// _kbhit can now be called again
Kninnug的答案會起作用,但是不必要地增加了處理器的使用率,因為while循環必須反復執行。 更好的解決方案是只使用
_getch();
在這種情況下,程序將等待用戶按下任何按鈕而不會浪費處理器時間
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.