简体   繁体   中英

C++, monitor for keyboard input

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?

我认为这篇文章接近你想要做什么而不涉及ncurses。

C ++对键盘一无所知,因此对此的任何答案都取决于您的操作系统及其库。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM