开发者

C++, monitor for keyboard input

开发者 https://www.devze.com 2023-01-10 10:49 出处:网络
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 poin

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?


I think this article comes close to what you want to do w/o involving ncurses.


C++ doesn't know anything about keyboards, so any answer to this depends on your operating system and its libraries.


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.


I'm not sure if this is standard C++, but you can use a C function that checks whether a key is available:

#include <conio.h>

int wmain()
{
    if(_kbhit())
    {
        char ch = _getch();
    }
}

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.


A library like Qt can help you quite a bit. You would create an "application" object, derived from QCoreApplication. In your override of QCoreAPplication::event(Event*), you would handle the event if it's a QKeyEvent containing Qt::Key_K. This is portable across Windows, Mac and Linux.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消