Lets say I had a loop running, but anytime during the loop I wanted the user to be able to press a key and make something else happen.
Any suggestions on how to do this? I am completely lost.
Lets say I had a loop running, but anytime during the loop I wanted the user to be able to press a key and make something else happen.
Any suggestions on how to do this? I am completely lost.
Plenty of ways to do this.....
you can do this (pseudocode), while the A key isnt pressed the loop runs, otherwise it quits (you can use the getch() function to do this)
orrrr, this way the loop will still continue, but do something differentCode:while(key 'a' is not pressed) { blahblah loopbody }
you can detect keystrokes (characters and numbers) with the getch() function from conio.h.. you should have conio already in your library, so just #include <conio.h>Code:bool a; while(some other while statement) { if a=true { blah loop body } else { blah other loop body } (as many ifs and elses as you need) }
you can detect all keys through windows, (assuming you are using windows) with windows.h.... there are key definitions that look something like this "VK_ENTER" or "VK_BACKSPACE"
you could do something like this
Code:if (keys[VK_ESCAPE]) // Was ESC Pressed? { Quit = true; }
Last edited by Shamino; 11-04-2005 at 02:25 AM.
getch() will halt execution of the loop if no key has been hit, you might want to look at kbhit() function to use in conjuction with getch(), depending on your os/compiler.
Thanks for your help, everyone. I'll try out these strategies soon.
There is a very simple way to use this:
// this loop will run non stop and enter every key u enter to c, note you can also use integers for this. also to make your program run better make sure you don't write stuff that doesn't suppose to change in the main while and only write them in the "if" of the kbhit, it makes a hugh difference when using graphics.Code:char c='1'; while (c!='q') // or anything else u want to use to exit loop { if (kbhit()) c=getch(); // this will require the conio.h library }
can anyone give an example like the full code coz i dont know how to implement this in my code! PLZ.
Code:while(!kbhit) { loop(); }
here is a very simple program that writes a charter on the screen non stop untill u enter 'q'
Code:#include <iostream.h> #include <conio.h> void main() { char c='1'; while (c!='q') { if (kbhit()) c=getch(); cout << c; } }