C++, how to control program flow with keyboard input

被刻印的时光 ゝ 提交于 2019-12-13 05:15:39

问题


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

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