views:

86

answers:

2

As most know getch waits until the user hits a key and then returns the value. Is there a way in order to just check if the user is currently hitting a key? Here is what I'm trying to do:

while(1){
char x = getch();
if (x){
//blah
}
else if(y == true){
//blah
}
}

Any suggestions?

+1  A: 

There's the kbhit() function (or _kbhit() if you're using Microsoft's libraries).

MSDN: http://msdn.microsoft.com/en-us/library/58w7c94c(VS.80).aspx

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

EDIT: As some commenters pointed out, it's not standard.

l33tnerd
I'll look into that.
Camoy
A: 

If you're just looking to pause the script until a key is pressed, then getch works, but if you want the character they pressed NOT to appear on screen (or you don't care about which key they pressed) you can use

system("pause > NUL");

It calls the Windows "pause" command and routes the displayed text and input (normally it says "Press any key to continue...") into an empty abyss.

The alternative is use a function like GetAsyncKeyState() and looping through all the input codes to see if any key is currently being pressed. This method works much better if you're trying to run a processing loop and want to break out when a user presses a specific key (for example, Escape). Using it to see if the user is pressing any key at all would involve wasting a good bit of processing power.

GigaWatt
getch doesn't echo.
PigBen