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.

Create a thread which will have only getchar. If something pressed then set a bool value in that thread. Of course in while loop will break when the bool value is set.

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 have getch() 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.

> 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.

i tried with kbhit() but isnt actually what i was looking for... im using borland c++ 3.1.

i have a for loop and i want that when the "h" key is pressed to do something.... however i dont wanna cease program's execution to wait for that key like getch() does.......

> 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.

> 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

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();

Edited 6 Years Ago by Nick Evan: n/a

> 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.

This article has been dead for over six months. Start a new discussion instead.