0

I am trying to get a keyboard input, but if it doesn't happen in about half a second I want it to continue to the rest of the loop. I tried using kbhit(); but it won't wait for the input, it just loops with out stopping. This is the loop in question:

    while(flags)
{
    gameing.updateDraw(0, 0);
    keyIn = getch();
    //Sleep(20);
    switch(keyIn)
    {
        case UP_ARROW:
                flags = gameing.updateDraw(-1, 1);
                break;
        case DOWN_ARROW:
                flags = gameing.updateDraw(1, 1);
                break;
        case WKEY:
                flags = gameing.updateDraw(-1, 2);
                break;
        case SKEY:
                flags = gameing.updateDraw(1, 2);
                break;
    }

All help will be greatly appreciated. I am trying to avoid using alarm();

2 Answers2

0

The comnented call to Sleep indicates that this is a Windows program using <conio.h> functionality, and not a *nix program using curses.

With <conio.h> you can use the kbhit function to check whether there is a keypress.

Place that in a loop that sleeps a little bit between each call.

More advanced you can use the Windows API. Its wait functions can wait on a console handle, with a specified timeout.

The C++ standard library does not have unbuffered keyboard input functionality.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • Thanks for the help. I figured a good way to do it with kbhit while(flags) { keyIn = 0; gameing.updateDraw(0, 0); Sleep(100); if(_kbhit()) The time was too much work compared to this, and as for Alf's answer I interpreted your answer as just using kbhit instead of getch(), and kbhit only returns that a key was pressed and not what key was pressed. – user3076703 Dec 07 '13 at 04:56
0

Try using something like ctime.h or chrono to get the time difference. Then do something like

long lastTime=CurrentTime();
int input=0;
while(!(input=kbhit()) && CurrentTime()-lastTime < 20);
if(input)
    // do stuff with input
// do all the other stuff
lastTime=CurrentTime();

Disclaimer. I'm not particularly familiar with kbhit and things, but based on a little bit of googling, this seems like it ought to work. Also the implementation of CurrentTime is up to you, it doesn't have to be a long or anything, I just chose that for simplicity's sake.

jgon
  • 698
  • 4
  • 11