I believe this is a very simple question, but I can't find a simple answer to it. I have an infinite loop, e.g. while(1)
, for(;;)
, and I need to break from the loop on a keypress. What is the easiest way to do this?
P.S.: I can't use getch
, cin.ignore
, or cin.get
because it stops the loop.
This checks if "left arrow" is being pressed or not:
Also this does not wait for anything. Just checks some flags.
Some other keys defined in winuser.h:
winuser.h must be included in windows.h
There is no "keyboard" in C++. You only have an opaque input data stream which your terminal populates occasionally with its own keyboard input. This is almost always a buffered, editable line-wise input, so you have no way of knowing when any given key was pressed.
You need a platform-specific method to communicate directly with your terminal on a lower level. One such library, fairly wide-spread and portable, is
ncurses
(a compatible Windows variant exists). Portable graphical application frameworks such as SDL and Allegro also provide raw keyboard handling.Below is a Windows console code that uses
kbhit()
and has an infinite loop. But if keyboard is hit, it breaks the loop and exits. If you have<conio.h>
, try this :Well, what you want is asynchronous input. All of the methods provided by
cin
wait for enter. You will have to use system-specific functions for that, or use a library that will do it for you.What you need to do is to not only process your logic in a while loop, but also listen from message pipe from your OS. If you want some more information about that one, please drop a comment.
EDIT: There's one other way, but I wouldn't recommend it as it can be non-portable I believe. The following code compiles and runs under VS2012RC.