Hello! here is what I wanna do:
I have a while() statement, and inside of it I have some instructions to repeat. My problem is that, I want somehow to stop that loop ONLY when I press a key... I it's kinda like getch() but getch() waits for a keypress.... Any help is appreciated :) Thanx in advance.
I assume you havegetch() available. Not all compilers do, making any code using it non-portable. But if you do, look to see if the compiler has a function called kbhit(). That's the function you're looking for.
WaltP
Posting Sage w/ dash of thyme
10,492 posts since May 2006
Reputation Points: 3,348
Solved Threads: 943
> somehow to stop that loop ONLY when I press a key
You need to say which OS and compiler you're using.
There is no portable answer to this question, so we need specifics.
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
> i tried with kbhit() but isnt actually what i was looking for
Did you try
if ( kbhit() ) {
ch = getch();
}
kbhit() doesn't do any reading, it only tells you if there's something there.
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
> i tried with kbhit() but isnt actually what i was looking for
Did you try
if ( kbhit() ) {
ch = getch();
}
kbhit() doesn't do any reading, it only tells you if there's something there.
In your above code the kbhit will pick up on the first keystroke. but
ch = getch();
will wait for another stroke, no?
I want to loop until a key is pressed. Then I want the ability to check that key that was pressed without havin to press it again
amishosh
Junior Poster in Training
59 posts since Oct 2006
Reputation Points: 10
Solved Threads: 0
It's been a while since I've used kbhit, so don't shoot me i I'm wrong ;); but if I remember correct kbhit will only tell you that a key is pressed. By saying ch = getch() you will actually get the key that is pressed, so if you want to loop until a char is pressed just use something like:
while (!(kbhit()));
ch = getchar();
Nick Evan
Not a Llama
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
> In your above code the kbhit will pick up on the first keystroke.
Read it again!.
kbhit() does NOT read a key, it merely tells you whether there is a key to be read.
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953