I'm new to coding and c++ and we were given an assignment to make a program that generates a random number and the user is asked to guess that number, the problem with my coding is that after every attempt by the user he/she is asked if they want to play again...but I want them to be asked if they want to play again after they have made all their attempts in finding the number and they get it right.
int main()
{
/* declaration of variables */
int G_num = 0;
int estimate = 0;
int attempt = 0;
char input;
char choice;
bool quit = false;
/* generates a random number to be estimated */
srand(time(0));
/* gives the range of the estimated number */
G_num = rand() % 20 + 1;
/* Welcome Message */
cout<<"\t\t\t\t_______________________________________________";
cout<<"\n \t\t\t\t| Welcome to Wayne's Random Number Generator |\n";
cout<<"\t\t\t\t_______________________________________________\n";
/* do while loop */
do
{
while (!quit)
{
cout<<"\n\nEnter a random number between 1 and 20: ";
cin>>estimate;
attempt++;
/* If guess is higher than the random number */
if (estimate > G_num)
cout<<"Number Too High Go Lower\n\n";
/* If guess lower than the random number */
else if (estimate < G_num)
cout<<"Number Too Low Go Higher\n\n";
/* If the user gets the number right */
else
cout<<"\nYAY! You found the Number. You got it in "<<attempt<<" tries\n";
/* Ask User if they wanna play again */
cout<<"Want to play again? (y/n): ";
cin>>choice;
if (choice =='y' || choice == 'Y')
{
cout<<"\nEverything will be reseted. You got this";
}
else // They Don't wanna play anymore
{
cout<<"\nWell Bye Bye Now!\n";
quit = true;
}
}
cout<<"\nHope you enjoyed the game!\n";
break;
}
while (estimate != G_num);
return 0;
}
also this assignment is due today and any help is much appreciated
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
int main()
{
srand(static_cast<unsignedint>(std::time(nullptr)));
bool quit {};
/* Welcome Message */
std::cout << "\t\t\t\t_______________________________________________";
std::cout << "\n \t\t\t\t| Welcome to Wayne's Random Number Generator |\n";
std::cout << "\t\t\t\t_______________________________________________\n";
while (!quit) {
int estimate {};
int attempt {};
/* gives the range of the estimated number */
constauto G_num {rand() % 20 + 1};
do {
std::cout << "\nEnter number between 1 and 20: ";
std::cin >> estimate;
++attempt;
if (estimate > G_num)
std::cout << "Number Too High Go Lower\n";
elseif (estimate < G_num)
std::cout << "Number Too Low Go Higher\n";
} while (estimate != G_num);
char choice {};
std::cout << "\nYAY! You found the Number. You got it in " << attempt << " tries\n";
std::cout << "Want to play again? (y/n): ";
std::cin >> choice;
quit = choice == 'n' || choice == 'N';
}
std::cout << "\nWell Bye Bye Now!";
std::cout << "\nHope you enjoyed the game!\n";
}