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. 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.
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. Call _getch
after the while-loop before the next one:
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. Much better solution is to just use
_getch();
In that case program will wait for user to press any button without wasting processor time
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.