Aravind .KEN Aravind .KEN - 1 month ago 8
C++ Question

How to prevent getch() from getting input data that was entered too soon?

Simple code to understand the problem:

string op;
int main()
{
cout<<"hi";
op=getch(); // or cin>>op
delay(2000) // delay for 2 sec.
cout<<endl<<" bye";
op=getch(); // or cin>>op
system("cls");
cout<<" MAGIc !! !!";
return 0;
}


What this code should be doing is:


  1. Print "hi"

  2. Wait for the user to press any key

  3. Wait for two seconds

  4. Print "bye"

  5. Wait for the user to press any key again

  6. Clear the screen

  7. Print "Magic"



Let's say there are two users: User A and User B.

Let's say User A presses the 'a' key and then waits for two seconds until "bye" is displayed, and then presses 'a' again and then sees the screen clear and "magic" get printed. Well User A is good, and there is no problem.

But let's User B is impatient. User B sees "hi" and immediately presses 'a' twice. Then after two seconds, he only sees the word "Magic". He never sees "bye" because the screen is cleared right away!

So the question is: how do I prevent the second
getch()
from getting input if an impatient user presses too many keys before "bye" is printed, so that they have to press another key after "bye" is printed and before the screen is cleared?

Answer

sorry for being too late. in your case use: FlushConsoleInputBuffer to clear getch buffer:

int main()
{
    cout<<"hi";
    op=getch();
    Delay(2000);
    cout<<endl<<" bye";

    FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE)); // flushing the buffer
    op=getch(); // or cin>>op
    system("cls"); 
    cout<<"  MAGIc !! !!";
    return 0;
}

user above can enter even 4 times a and everything will be alright.

  • it's so stupid to clear cin's buffer without using it