Take the 2-minute tour ×

Is it possible to exit a C++ loop based on keyboard input without actually having to input something each iteration?

For instance

while(checkkeyboardinput != 'q')
     do work

I feel that this is very easy, but google isn't helping me, and I can't remember how to do this. Thanks for the help.

EDIT: I'm using VS2008

share|improve this question
Which platform are you using? Winodows, Linux, Mac? –  Colin Mar 30 '09 at 4:04

3 Answers 3

up vote 4 down vote accepted

Try _kbhit(). As far as I know it checks if there is any keyboard input waiting in the buffer.



Checks the console for keyboard input.

int _kbhit( void );

Return Value

_kbhit returns a nonzero value if a key has been pressed. Otherwise, it returns 0.


The _kbhit function checks the console for a recent keystroke. If the function returns a nonzero value, a keystroke is waiting in the buffer. The program can then call _getch or _getche to get the keystroke.

share|improve this answer

If you are using ncurses, you can, very easily, with getch(). However, there is not standard way to do what you want.

share|improve this answer

You neglected to mention what OS you're running. Getting keyboard input is OS dependent (even library dependent -- eg. how to do it with GTK is obviously GTK specific.)

Well, GTK runs on multiple OS'es, so... but you get the idea. You need to specify a bit more about the environment your working in to get a reasonable answer.

share|improve this answer

Your Answer


