#include <iostream>
int main(){
int num;
char rerun;
do {
std::cout << "Please guess a number: ";
std::cin >> num;
if (num == 5)
std::cout << "Hey! You weren't supposed to enter 5!";
else{
do{
std::cout << "Please guess again: ";
std::cin >> num;
}
while (num != 5);
std::cout << "\n Hey! You weren't supposed to enter 5!";
std::cout << "\n Do you want to play again? (y/n)";
std::cin >> rerun;
}
}
while (rerun == 'y' || rerun == 'Y');
}
#include <iostream>
int main()
{
int num;
char rerun;
do
{
std::cout << "Please guess a number: ";
std::cin >> num;
if (num == 5)
std::cout << "Hey! You weren't supposed to enter 5!";
else
{
do
{
std::cout << "Please guess again: ";
std::cin >> num;
} while (num != 5);
std::cout << "\n Hey! You weren't supposed to enter 5!";
std::cout << "\n Do you want to play again? (y/n)";
std::cin >> rerun;
}
} while (rerun == 'y' || rerun == 'Y');
}
With a few blank lines and having the {}s line up in the same column makes the code much easier to read.
I do question the second do/while in the else block. That just does not seem like it should be there, but realize that I have not tested the program yet.
For a limit I would define a variable std::size_t count{}; where "size_t" is another name for "unsigned int" and the empty {}s will initialize the variable to zero.
In the second do/while loop I would add one to count and change the while condition to: while (num != 5 && count < 6); and see if that works. I see more when I test the code.
Above main I put the line constexpr std::size_t MAXTRIES{ 5 };.
In main I defined the variable "count" and set it to 1. Because the first guess is after the outer do/while loop.
Looking at my code above I moved lines 24 and 25 outside the else block so that the if statement would also see these line and I added if (std::toupper(rerun) == 'Y') count = 1; // <--- Reset "count" for next play. . Otherwise it would just keep adding to "count" and become unusable.
In the else block I would consider changing the message to reflect that the maximum number of tries has been reached. Maybe even an if/else one part for reaching the max tries and the other for entering 5.
Line 18 is set up correctly, but "count" is always 1. Inside the do/while loop you need to change the value of count with count++; otherwise the while condition will always be true unless you enter 5 for "num"
When you find a problem like this I usually put a break point in the program so I can check the value of "count" . Or you could put a cout statement as the last line of the do/while loop to print the value of "count.
Hope that helps,
Andy
Edit:
P.S. the way to stop before 10 guessed is when you enter 5.
And Thomas1965's example is a very good alternative.