tags:

views:

145

answers:

6

Hi, 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?

A: 

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

tpdi
any idea where I should start looking?
Laharah
Tell us what operating system(s) you want this code to work under.
tpdi
This answer should be a comment.
Duracell
*nix is what I'm using a.t.m.
Laharah
A: 

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.

Will A
Regardint tpdis comment - absolutely correct - I'm assuming Windows.
Will A
know anything for *nix systems?
Laharah
A: 

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.

bart
It isn't standard, that is Windows-only.
Zan Lynx
+4  A: 

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

Duck
A: 

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.

MSalters
A: 

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.

Ricardo