You can use kbhit()
which tests if a key has been pressed, before committing to the blocking function getch()
. The loop below uses clock()
to check for timeout.
#include <conio.h>
#include <stdio.h>
#include <ctype.h>
#include <time.h>
#define TIMEOUT 5 // seconds
int main(void)
{
clock_t tstart = clock();
int v1 = 'y'; // default key press
while((clock() - tstart) / CLOCKS_PER_SEC < TIMEOUT) {
if(kbhit()) {
v1 = getch();
break;
}
}
if(tolower(v1) == 'y')
printf("Example\n");
return 0;
}
It's particularly useful in a game, where you don't want to sit there waiting for a key press, and then it isn't quite so simple to use. When you press a function key or a cursor key getch()
returns two successive characters, the first is an "escape" value which must be checked for.