问题
I have a main routine that loops infinitely. By changing bool variables using keyboard input, I want to be able to control whether certain if{} statements within that loop are getting called. I found this thread:
C non-blocking keyboard input,
but it seems excessively laborious and complicated for seemingly basic functionality. Is there an easier way to do it?
回答1:
You'll have to use the OS/Firmware/Framework/environment API to get input events, or use a library that do this for you. Anyway, there is no built-in way of doing this in C++.
I often use OIS in games. It's cross-platform and easy to use. Not sure it's useful for other cases than games but it does the job for you.
回答2:
The SDL library is one way to do it cross-platform. Here's an example of polling keyboard events.
回答3:
Put the main routine in a thread, then have something like
static char mode = ' ';
while(mode != 27) // to allow Esc to end program
{
mode = _getch();
}
Threaded code can then do different things based on what key was pressed.
来源:https://stackoverflow.com/questions/5203737/c-how-to-control-program-flow-with-keyboard-input