为什么_kbhit()只能在C程序中运行一次?

时间:2013-10-17 19:13:38

标签: c++ c

我刚刚编写了这个小程序,它应该等待用户在打印每一行之前键入内容,但它只适用于第一个_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;
}

function reference中没有_kbhit()仅在程序中运行一次的信息。

2 个答案:

答案 0 :(得分:2)

虽然它没有在该文档页面中明确说明,但您必须使用键击(使用getchgetche),否则_kbhit仍会看到它。在下一个循环之前的while循环之后调用_getch

while(_kbhit() == 0);
_getch();
// _kbhit can now be called again

答案 1 :(得分:2)

Kninnug的答案会起作用,但是不必要地增加了处理器的使用率,因为while循环必须反复执行。 更好的解决方案是只使用

_getch();

在这种情况下,程序将等待用户按下任何按钮而不会浪费处理器时间