Sign in to follow this  
Raisor

Help with keyboard input

Recommended Posts

I'm sorry if this has been asked before but I couldnt find it searching (probably due to my search terms) but I was wondering how I allow someone to exit a for loop by pressing the esc key without interrupting the for loops output in c++. Basically I would like to know how to allow the for loop to continue running until the escape key is pressed and then exit if it is. example:
for ( i = 0; i < 100; i++ )
{
    cout << i;
    cin >> keyboard_input;
    if ( keyboard_input = 27 ) break;
}
Using cin or getch stops the output and waits for a key to be pressed... Any help would be appreciated.

Share this post


Link to post
Share on other sites
You could take a look at kbhit() and getch().

example:



for( i = 0; i < 100; i++ )
{
cout << i;

if( kbhit() )
{
key = getch();
if( key == 27 )
break;
}
}




Forgot to mention though.
Both of those functions are not ANSI standard.

Share this post


Link to post
Share on other sites
I think this is what you're looking for..


#include <iostream>
#include <windows.h>

int UserInput = 0;
bool iExit = false;

int main()
{
int number = 0;
while(iExit == false)
{
if( ::GetAsyncKeyState(27) & 0x8000f ) { iExit = true; }

// Do whatever you want, the loop will continue until you press Esc
// For proof increase number on every loop and display it..
number++;
std::cout << number << "\n";
}
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this