[英]Why does _kbhit() only work once in a C program?
I just wrote this little program, that should wait for the user to type something before printing each line, but it only works for the first _kbhit(), afterwards it does not wait anymore. 我只是写了这个小程序,应该在打印每行之前等待用户键入内容,但是它仅适用于第一个_kbhit(),之后不再等待。 Why's that?
为什么?
#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;
}
There's no information in the function reference that _kbhit() only works once in a program. 函数参考中没有信息表明_kbhit()在程序中只能运行一次。
While it doesn't say it that explicitly in that documentation page, you have to consume the keystroke (with getch
or getche
), otherwise _kbhit
will still see it. 尽管在该文档页面中没有明确说明,但您必须使用击键(使用
getch
或getche
),否则_kbhit
仍然会看到它。 Call _getch
after the while-loop before the next one: 在while循环之后的下一个循环之前调用
_getch
:
while(_kbhit() == 0);
_getch();
// _kbhit can now be called again
Kninnug's answer will work, but it raises processor ussage needlessly, because while loop must execute over and over. Kninnug的答案会起作用,但是不必要地增加了处理器的使用率,因为while循环必须反复执行。 Much better solution is to just use
更好的解决方案是只使用
_getch();
In that case program will wait for user to press any button without wasting processor time 在这种情况下,程序将等待用户按下任何按钮而不会浪费处理器时间
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.