C++,键盘输入监视器
我正在温习我的一般编程技能,但遇到了一个障碍。我正在编写一个模拟兔子群的程序。一旦该程序启动,它就是自治的,但是,在任何时候用户都应该能够按“k”键将人口剔除一半。我想不出一种方法可以在不暂停程序等待用户输入的情况下执行此操作。我也想不出办法让程序立即响应(程序使用 sleep 命令半实时运行)。有没有一种方法可以在不使用多线程和多年经验的情况下实现这一目标?
I'm brushing up on my general programing skills and I've come across a snag. I'm writing a program that simulates a colony of bunnys. Once this program starts it is autonomous, however, at any point the user should be able to press the 'k' key to cull the population by half. I can't think of a way to do this without pausing the program to wait for user input. Nor can I think of a way to make it so that the program will respond immediately (the program runs in semi-real time using the sleep command). Is there a way to accomplish this without multi-treading and years more experience?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
像 Qt 这样的库可以为您提供很大帮助。您将创建一个派生自 QCoreApplication 的“应用程序”对象。在重写
QCoreAPplication::event(Event*)
时,如果该事件是包含Qt::Key_K
的QKeyEvent
,则您将处理该事件。它可以跨 Windows、Mac 和 Linux 移植。A library like Qt can help you quite a bit. You would create an "application" object, derived from
QCoreApplication
. In your override ofQCoreAPplication::event(Event*)
, you would handle the event if it's aQKeyEvent
containingQt::Key_K
. This is portable across Windows, Mac and Linux.尝试ncurses,它在 UNIX 环境中非常标准。它具有特殊功能,可以超时等待用户输入,以防无人按下任何键。
Try ncurses it's pretty standard in UNIX enviorments. It has special functions to wait for user input with timeout in case nobody press any key.
我认为这篇文章< /a> 接近于您想要做的不涉及 ncurses 的事情。
I think this article comes close to what you want to do w/o involving ncurses.
C++ 对键盘一无所知,因此任何答案都取决于您的操作系统及其库。
C++ doesn't know anything about keyboards, so any answer to this depends on your operating system and its libraries.
看一下 @ GetAsyncKeyState Windows API称呼。您应该能够找到一个合适的位置将其插入代码中以检测按键。
Take a look @ the GetAsyncKeyState Windows API call. You should be able to find a suitable place to shoehorn this into your code to detect the keypress.
我不确定这是否是标准 C++,但您可以使用 C 函数来检查密钥是否可用:
编辑:正如 Zan Lynx 提到的,这不是标准 C++,甚至不是标准 C,这就是为什么没有标头。它可以在 Visual C++ 或 DOS C++ 编译器中正常工作。
I'm not sure if this is standard C++, but you can use a C function that checks whether a key is available:
EDIT: as Zan Lynx mentioned, this is not standard C++, or even standard C, which is why there is no header. It will work fine in Visual C++ or DOS C++ compilers.