1

I have a console game where the player uses the keys W, A, and D to move. I get the key input using the getKeyState() function in the <windows.h> lib.

However, when I prompt the player to play again using std::cin, all the keyboard inputs are shown, and the user has to delete all of the characters manually.

You could encounter the same problem if something like this happens:

Sleep(10000)  // user types something here
char input;
std::cin << input;  // user sees what they typed here

Is it possible to clear this so the user does not see what they previously typed?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    What do you mean by "all the keyboard inputs are shown and the user has to delete all the characters manually"? There is no output in the code posted. Please provide [mcve] of code that compiles and reproduces the problem, including example input and output. – Yksisarvinen Jul 19 '22 at 23:20
  • 2
    Maybe you want [_getch()](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/getch-getwch?view=msvc-170). This is how we used to do it way back in the day. Before Windows, even. – paddy Jul 19 '22 at 23:21
  • 1
    @Yksisarvinen in the code that I supplied, let's say the user types "hello" during the time the program is sleeping. When the user is prompted for input on line 3, the "hello" that they typed will appear. I do not want the user to see what they typed before the std::cin. – AlexanderJCS Jul 19 '22 at 23:46
  • 1
    @paddy thanks for your suggestion. Doing while (_kbhit()) { _getch(); } worked. – AlexanderJCS Jul 19 '22 at 23:48
  • 1
    Using `std::cin` is not the ideal way to solve your problem. If you are using a console, then I recommend that you use the function [`ReadConsoleInput`](https://learn.microsoft.com/en-us/windows/console/readconsoleinput). You can use [`WaitForSingleObject`](https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobject) with a console handle to wait for new input to be available. – Andreas Wenzel Jul 20 '22 at 00:09
  • 1
    @AlexanderJCS It should be `std::cin >> input;` instead of `std::cin << input;` – Jason Jul 20 '22 at 02:10
  • Does this answer your question? [How do I flush the cin buffer?](https://stackoverflow.com/questions/257091/how-do-i-flush-the-cin-buffer) – starball Aug 12 '22 at 06:07
  • @DavidFong thank you for your help. I was able to clear the input buffer by doing while (_kbhit()) { _getch(); }. – AlexanderJCS Aug 13 '22 at 15:52

0 Answers0