GetAsyncKeyState creates problems with cin

I am currently creating a console game for school and am having problems using GetAsyncKeyState for my main menu. My main menu runs in an endless loop that only breaks after a key is pressed. For example, I have:

if(GetAsyncKeyState('1')) { Play(); break; } 

This, alone, works great. The problem is that in my Play () method, I have a cin instruction right from that bat, and "1" from the menu () is included in my Play (). I tried cin.clear () to no avail, and cin.ignore (...) prevents an instant change from Menu () to Play (). Is there any way to prevent this?

+4
source share
1 answer

Try before calling Play()

 FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE)); 

In addition, when you use GetAsyncKeyState, you must mask everything except the older one, for example:

 if ((GetAsyncKeyState('1') & 0x8000) != 0) 

See the documentation in the Return Value section for an explanation of why: http://msdn.microsoft.com/en-us/library/windows/desktop/ms646293%28v=vs.85%29.aspx

+3
source

Source: https://habr.com/ru/post/1385810/


All Articles