Hi there, this is a problem I've been having for a while, but it was never particularly troublesome until now.
I was wondering if there's a way to stop the infinite feedback from a while loop without using a break
#include <iostream>
#include <string>
int main()
{
std::cout << "pick a number\n";
std::string number;
std::cin >> number;
while(true)
if (number == "1")
{
std::cout << "your class is 1\n";
break;
}
elseif (number == "2")
{
std::cout << "your class is 2\n";
break;
}
else
{
std::cout << "sorry, try again\n";
}
std::cout << "thanks for playing\n";
system("pause");
}
If you give this a quick run and type in a 3, you'll get a continuous string of spam from the else output.
What I'm wondering is if there's a way to go back to the start of the loop?
You are going back to the start of the loop, but the value of "number" never changes, because it is set before the loop. Put while(true) before std::cout << "pick a number\n";.
Also, a while should be followed by brackets ({ }) to make sure the entire loop body is executed. Now, only the first statement is evaluated as the loop [but if-else is treated as 'one statement', so you won't notice a difference with the current code. It will mess up your code if you move the while(true) to the start of the main).
Thanks very much for the help. I have a couple of questions though. Firstly, what does return 0 do?
Second, that thread was very useful, thank you for that. However it didn't really explain what to use instead. I'm used to using system() or simply setting break points. I was taught another way but I'm afraid I'm drawing a blank
Again, thanks for the help, especially in such a quick response!
return 0; tells the calling environment that the program exited successfully. For your current projects it probably makes no difference, and I even think modern compilers assume the return 0 by default anyway, but it's still considered good practice.
To avoid system("pause"), you can use a variety of tricks, going from easy to very complicated. Personally, I use breakpoints or a simple piece of code:
1 2 3
std::cout << "Enter any number to quit.\n";
std::cin >> t; // Random variable from the code somewhere.
return 0;
Code-wise, I think that's as easy as it gets. I simply overwrite the value of a random variable (here: 't'). The program is about to end anyway, so I'm not doing any damage.
The reason your code is in an infinite loop is your while statement. While true ... then you have nested if statements. while true means loop, and if 3 cout ......, so you will infinitely cout the statement because its true.
i would remove the while. You have to ask yourself what you want your program to do exactly. Then figure whats the best way to create that.
Nickoolsayz, the loop is not infinite as it is broken if number = 1 or 2, however I need it to be a possibly infinite loop in case the player keeps entering a number that is not 1 or 2.