In this Guess My Number Program, you have 20 tries to try and get the number 1-500. It tells you if its bigger or smaller. Anyway, I run it and I enter a random number. But regardless of what I enter, it says it's bigger or smaller (fine with that) but then it goes to saying "Congratulations, you have won. Blah blah blah".
I can keep entering numbers but it'll just keep congratulating me even if I didn't get it correct.
Thanks. I fixed the spelling errors and stuff. The problem still exists. Here's an example of what I inputted.
"I have generated a number. Attempt to guess it! (1-500)"
"Remember - you have only twenty tries!"
"12"
"Your guess is too small"
"Congratulations! You guessed the number in 3 tries!"
"Want to restart the game? Press 'Y' or 'y' if you do."
You'll need to add a loop, right now the programs just going straight to the finish.
Make it loop 20 times, when the guess is correct it can break the loop to the congratulations message otherwise do the failure thing.
Try a do while loop
Here is my do-while loop attempt. I don't really understand how it works so that must be where my problem lies. I think the problem now is when the do-while loop activates, it keeps looping until tries is 20 and not going back and asking for another guess.
#include <iostream>
#include <ctime>
usingnamespace std;
int main()
{
restart:
int number;
int guess;
int tries;
char response;
srand(time(0));
number = rand() % 500 + 1;
tries = 0;
cout << "I have generated a number. Attempt to guess it! (1-500)" << endl;
cout << "Remember - you have only twenty tries!" << endl;
cin >> guess;
do
{
cout << "Your number is too big! Try again." << endl;
tries++;
} while (guess > number && tries < 20);
do
{
cout << "Your number is too small! Try again." << endl;
tries++;
} while (guess < number && tries < 20);
if (tries == 20)
{
cout << "Sorry! That was your twentieth try. Game Over!" << endl;
cout << "The number was " << number << "." << endl;
cout << "Try again? (Y/N)" << endl;
cin >> response;
if (response != 'Y' || response != 'y')
{
return(0);
}
else
{
system("CLS");
goto restart;
}
}
if (guess == number && tries <= 20)
{
cout << "Congratulations! You guessed the number in " << tries << " tries!" << endl;
cout << "Want to restart the game? Press 'Y' or 'y' if you do." << endl;
cin >> response;
if (response != 'Y' || response != 'y')
{
return(0);
}
else
{
system("CLS");
goto restart;
}
}
}
P.S. Thanks! No wonder - I forgot to even declare what tries was in the first place!