Input during loop
I am attempting to allow the user of my program to be able supply an keyboard input while a for loop is looping. The input is going to be used to stop the for loop.
Here is the loop:
It would also be good if I could allow the user to push any key to exit the loop, but I am unsure how to go about this.
case 1: for (int key = 0; key == 0; key+0)
hunger = hunger + 10;
if (hunger >= 60 && hunger <= 80)
health = health - 10;
else if (hunger >= 80 && hunger <= 180)
health = health -10;
cout << "::Pet's Stats::\n\n\n"
<< "Health: " << health << "\n"
<< "Hunger: " << hunger << "\n\n\n"
<< "Press 1 and enter to get back to the pet care menu!\n\n";
cin >> key;
Do you mean that you want the loop to continue cycling unless it sees user input (i.e. not stop and wait for user input each cycle)?
If so, there isn't really a standard way of doing it, but you can find some information here.
I'm just looking for a way to use the goto function to get back to my main menu I need to be able to do this at any point while my loop is looping and its ok for the loop to stop once I've gone back to my menu but it must keep looping until I press a key or press 1 and enter or something like this.
when I try to use cin it stops the loop from working properly!
I think you probably mean a kbhit() style function, again this (using conio.h) is non standard but the faq link is here kbhit - C++ Function Reference
Bear in mind to keep track of all your data status when you exit the loop, that is if you wish the kbhit to perform a 'pause' like function then you need to ensure that when the loop resumes that everything picks up where it left off, variable values etc.
In a 'stop' scenario it is a bit simpler where you can just call an Init() function to reset everything prior to a restart - or reset with values according to the new menu choice etc etc.
After a load of googling I found out about the kbhit function and I used it in my code and it works great. If I had not found it your help would have been spot on so thanks for that.
Originally Posted by rogster001