how to clear the key buffer while using kbhit() and getch()

狂风中的少年 提交于 2020-01-11 13:05:56

问题


heu so I'm using the above stated windows functions which luckily are for windows 2000 and up, but in making a game on the console I've run into a problem: as soon as a key is pressed the console gets passed the kbhit() function no matter if a key is not pressed again...

is there some way I can clear the keyboard press buffer so you can't get passed kbhit without a new keypress?

If a new lib download is requires I guess I could... but I'm hoping for a windows standard way!

Thanks!!


回答1:


Whoever told you that kbhit() was a Windows function misinformed you. kbhit(), getch() and their relatives are actually part of the (C language bindings to the) MS-DOS API. Their presence in the runtime libraries for OS/2, Win32, and other C/C++ compilers is simply to be a porting aid for MS/PC/DR-DOS programs. The library maps them onto whatever native mechanism exists for accessing the keyboard, if there is one at all, and usually only in the right way for TUI, not GUI, applications to access the keyboard.

If you're writing a new TUI application, don't use the MS-DOS API. Use the proper, native, API for the platform that you're targetting, such as the Win32 Console API or the OS/2 Console API, or the POSIX General Terminal Interface (via ncurses or some such).

When you do, you'll read their documentation and find out how to perform a destructive "get" of the keyboard input after doing a non-destructive "peek". Or indeed how to flush the buffer in its entirety if that is what you want to do.




回答2:


The obvious choice would be FlushConsoleInputBuffer



来源:https://stackoverflow.com/questions/5862770/how-to-clear-the-key-buffer-while-using-kbhit-and-getch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!