0

I am trying to have the function getch() of the C language in Windows to work only for a few seconds.

#include <stdio.h>
#include <windows.h>
int main()
{
    int v1, v2;
    v1=getch();//I want this getch to only be activated for a few seconds
    printf("Example");//That to activate the next function, even if the person reading this programm doesn't click in any key
    return 0;
}
NickOlder
  • 37
  • 1
  • 3

2 Answers2

1

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.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • Note: it is recommended to use '_kbhit' and '_getch' instead of 'kbhit' and 'getch' on windows: 'C4996 'kbhit': The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: _kbhit. See online help for details. ' – Jamie Nicholl-Shelley May 08 '23 at 21:55
0

you need to use the ncurse library and call:

  • initscr or newterm to initialize the screen
  • timeout with a positive delay. Otherwise, it will not be blocking.

Read more here