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'm writing a program that simulates a colony of bunnys. Once this program starts it is autonomous` --- what do you have to do with the first bunny to get the program going? – Peter Ajtai Aug 02 '10 at 23:11
-
the constructor for the colony seeds it with 5 bunnies randomly male or female – Laharah Aug 02 '10 at 23:31
-
Possible duplicate: http://stackoverflow.com/questions/448944 -- although there's no C++ abstraction. Also check http://rabbit.eng.miami.edu/info/functions/asynchkbd.html – jweyrich Aug 02 '10 at 23:35
6 Answers
C++ doesn't know anything about keyboards, so any answer to this depends on your operating system and its libraries.

- 34,554
- 11
- 80
- 120
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.

- 24,780
- 5
- 50
- 61
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.

- 1,100
- 11
- 14
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.

- 173,980
- 10
- 155
- 350
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.

- 1,778
- 1
- 19
- 32