2

First, sorry for my bad English. I'm using GetTickCount() function included in windows.h and getch() included in conio.h.

What I precisely want is to give user a time limit to input char. If time limit lapses, program continues to execute, skipping the wait for user to input the char.

char ch='A';
DWORD start_time, check_time;

start_time=GetTickCount();
check_time=start+500; //GetTickCount returns time in miliseconds, so I add 500 to wait input for half a second.

while (check_time>GetTickCount()) {
ch=getchar();
}

//do stuff with char with initial value of 'A' if user didn't enter another char during 500ms of wait.

But getchar() stops executing the program and waits for user to input char for indefinite time. Is there an easy solution to bypass this wait, and continue if 500ms passed?

EDIT:

Based on your tips, i wrote this and it works! Thank you guys!

while (!kbhit()&&(check_time>GetTickCount()))
    {
        if (kbhit())
        {
            ch=getch();
            break;
        }
    }
Hajzenberg
  • 73
  • 2
  • 7

2 Answers2

2

As proposed by Charlie Burns the kbhit function from conio does exactly what you want : it looks it a key was hit.

You could do :

DWORD start_time, check_time;

start_time=GetTickTime();
check_time=start+500; //GetTickTime returns time in miliseconds, so I add 500 to wait input for half a second.
char ch = 0;
char hit =0

while (check_time>GetTickTime()) {
    if (_kbhit()) {
        hit = 1;
        ch = _getch();
        if (ch  == 0) ch = _getch() // an arrow key was pressed
        break;
    }
}
// if hit == 0 we got a timout, else ch is the code of the key

Beware : untested ...

Serge Ballesta
  • 136,215
  • 10
  • 111
  • 230
  • Yes, that solves the problem! I got the similar solution, but I think your might work better for some situations. For some reason I'm not allowed to up vote your post. – Hajzenberg Nov 07 '14 at 19:51
1

Windows solution using GetTickCount() and GetAsyncKeyState(...):

This approach uses the non-blocking Windows API function GetAsyncKeyState(), with GetTickCount (I do not have GetTimeTick) But that can easily be changed out for GetTickCount() for your system.

keyPressed(...) looks at each of the 256 keys, including virtual keys of a key board, and returns true if anything has been pressed:

#include <windows.h>  

BOOL keyPressed(char *keys)
{
    for(int i = 0; i<256; i++)
        if(GetAsyncKeyState(i) >> 8) return 1;
    return 0;   
}    

Test for keyPressed function:

#define TIME_LIMIT 10

int main(void)
{
    int c=0;
    char *key;  
    DWORD Start, Duration=0; //unsigned long int

    key = calloc(256, 1);

    Start = GetTickCount();

    memset(key, 0, 256);
    while((Duration < MAX_TIME)&&(!keyPressed(key))) // \n character
    {
        Duration = GetTickCount() - Start;
    }
    if (Duration < MAX_TIME) printf("in-time\n");
    else printf("Out of time\n");

    getchar();

    free (key);
    return 0;
}
ryyker
  • 21,724
  • 3
  • 41
  • 81