user3496846
user3496846

Reputation: 1665

How do I clean input buffer before using getch()?

So, I am using GetAsyncKeyState() to see when some key is pressed. But, after using it I need to use getch(). But it seems that getch() gets whatever GetAsyncKeyState() got before again. That is the version of my simplified code:

#include <graphics.h>

int main()
{
    initwindow(100, 100);

    while(true)
    {        
        if (GetAsyncKeyState(VK_RETURN))    //wait for user to press "Enter"
            break;
        //do other stuff
    }

    getch();    //this is just skipped

    return 0;
}

I think I need to clean the input buffer before using getch(). But how? PS: GetAsyncKeyState() is a must-use for me and I have not found any substitute for getch(), which could work with BGI window and which would fix the problem. Hoping for some advice and thank you.

Upvotes: 2

Views: 9381

Answers (2)

Benjamin Lindley
Benjamin Lindley

Reputation: 103741

Use FlushConsoleInputBuffer

FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));

Upvotes: 3

rajenpandit
rajenpandit

Reputation: 1361

It is skipping getch() call beacuse of enter pressed by user for the previous input, and getch is getting that char, the function fflush(stdin) we flush the input stream. so that getch() will read the fresh input from input stream.

#include <graphics.h>

int main()
{
    initwindow(100, 100);

    while(true)
    {        
        if (GetAsyncKeyState(VK_RETURN))    //wait for user to press "Enter"
            break;
        //do other stuff
    }
    fflush(stdin);
    getch();    //this is just skipped

    return 0;
}

Upvotes: 0

Related Questions