0

I am having issues with repeating key checking using a function that utilizes getch().

Here is a code example:

static char g_keybuffer[256];
_Bool IsKeyDown(char c)
{
    char ch;
    if(kbhit())
        ch = getch();

    if(ch == -32 || ch == 224)
    {
        ch = getch();
    }

    g_keybuffer[ch] = 1;
    if(g_keybuffer[c] == 1)
    {
        g_keybuffer[c] = 0;
        return 1;
    }

    return 0;
}

/*
 * 
 */
int main(int argc, char** argv) {
    while(1)
    {
        if(IsKeyDown('a'))
        {
            printf("Test\n");
        }
        if(IsKeyDown('a'))
        {
            printf("Hello\n");
        }
        else if(IsKeyDown('b'))
        {
            printf("World\n");
        }
        Sleep(100);
    }
    return (EXIT_SUCCESS);
}

I know why the problem occurs. When a key is pressed, kbhit is true once per loop, and sets ch to the character retrieved from the buffer. When IsKeyDown is used, if it is equal to the parameter, the key in the buffer g_keybuffer is set equal to zero to avoid having a key be "down" infinitely. The problem with this is if you want to check if the same key is down more than once, only the first instance of IsKeyDown will be ran, with the rest being invalid due to the g_keybuffer of the key now being 0.

Does anyone know how I can change IsKeyDown to give it the ability to check the same key multiple times per looping? I'm stuck.

5
  • did you try cin.ignore()? Jan 17, 2014 at 5:15
  • 1
    I haven't looked too closely to your code, but you should realize that ch is uninitialized when kbhit return false. that will mess up your function
    – tay10r
    Jan 17, 2014 at 5:15
  • 1
    @theharshest this isn't C++
    – tay10r
    Jan 17, 2014 at 5:16
  • @Taylor Flores Initializing ch does not appear to make a difference in the outcome of the code
    – NAME__
    Jan 17, 2014 at 5:18
  • duplicate: stackoverflow.com/questions/21177800/…
    – Brandin
    Jan 17, 2014 at 7:37

1 Answer 1

0

Your problem is because you are setting g_keybuffer[c] to 0 after you get a hit for the key state. I'm guessing you have done this to avoid getting the same result twice - but that is just a workaround. The only way to do what you want to do properly is to choose a library that is actually made to capture the keyboard state.

Most graphics libraries have functions for capturing keyboard states. I don't know of any solutions thought that don't involve a little overhead if you are just writing a small program.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.