Clear 'ENTER'

So, I have this on my code:

1
2
3
4
   cout << "Push 'ENTER' to continue";
   
   while (GetAsyncKeyState(VK_RETURN) & 0x8000) {}		// if enter is already pressed, wait for it to be released
   while (!(GetAsyncKeyState(VK_RETURN) & 0x8000)) {}		// wait for enter to be pressed 


My question: when I press 'ENTER', I think that 'ENTER' stays in the buffer and it will be shown next time I want to write something to the console (using cin). How do I clean it? I've tried using cin.clear() and cin.ignore(1000, '\n'), but it does nothing that I want...
Does it work if you use cin.get() instead of the whiles?
No, that way, cin.get() gets an error... :P
What error?
What error?
You're saying if I do this, right?

1
2
cin.get(GetAsyncKeyState(VK_RETURN) & 0x8000);
cin.get(!(GetAsyncKeyState(VK_RETURN) & 0x8000));


Then the error is: "no instance of overloaded function [...] matches the argument list arguments types are: (int). object type is: std::istream"
Last edited on
No, I'm saying do this:
1
2
cout << "Push 'ENTER' to continue";
cin.get();
Thanks for the information, but no, it's still there... :(
You are correct: GetAsyncKeyState() does not modify the input buffer.

However, you still have a problem. The current state of the input buffer does not necessarily match the return value of GetAsyncKeyState().

However, you are thinking about this a little wrong. This kind of code assumes that there must be a human sitting at the PC, and that he is waiting on you to provide more input. As a result, you must clear the input buffer.

FlushConsoleInputBuffer( GetStdHandle( STD_INPUT_HANDLE ) );

After flushing the buffer, you can use a variation of the following:
http://www.cplusplus.com/forum/beginner/4533/#msg19959

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <windows.h>

void wait_for_press_enter( const TCHAR* prompt = NULL )
  {
  TCHAR  ch;
  DWORD  mode;
  DWORD  count;
  HANDLE hstdin = GetStdHandle( STD_INPUT_HANDLE );

  // Prompt the user
  if (prompt == NULL) prompt = TEXT( "Press the ENTER key to continue..." );
  WriteConsole(
    GetStdHandle( STD_OUTPUT_HANDLE ),
    prompt,
    lstrlen( prompt ),
    &count,
    NULL
    );

  // Switch to raw mode
  GetConsoleMode( hstdin, &mode );
  SetConsoleMode( hstdin, 0 );

  do
    {
    // Wait for the user's response
    WaitForSingleObject( hstdin, INFINITE );

    // Read the (single) key pressed
    ReadConsole( hstdin, &ch, 1, &count, NULL );
    }
  while (ch != 13);

  // Restore the console to its previous state
  SetConsoleMode( hstdin, mode );
  }

Hope this helps.
Topic archived. No new replies allowed.