tags:

views:

774

answers:

3

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

+3  A: 

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

rlbond
+4  A: 

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

http://msdn.microsoft.com/en-us/library/58w7c94c%28VS.80%29.aspx

_kbhit

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.

Remarks

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.

m3rLinEz
+1  A: 

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.

smcameron