I am stuck with this program. So far the user can guess an age and if they get it right the program ends but when the program is asking the user if they want to try again. I get stuck. How do I have it where the user can tell the program Yes they want to try again or if they dont the loop ends. Heres the coding so far. Its an assignment I am stuck on.
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int main()
{
srand(time(0));
int age = rand() % 100;
int guess = 0;
while (guess != age)
{
cout <<"Guess an age between 1-100:";
cin >>guess;
if (guess == age)
cout <<"You guessed the right age!"<<endl;
elseif (guess != age)
cout <<"Sorry, you guessed the wrong age. Do you want to try again?"<<endl;
}
return 0;
}
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int main()
{
srand(time(0));
int age = rand() % 100;
char ch;
int guess = 0;
do
{
cout <<"Guess an age between 1-100:";
cin >>guess;
if (guess == age){
cout <<"You guessed the right age!"<<endl;
break;
}
elseif (guess != age){
cout <<"Sorry, you guessed the wrong age. Do you want to try again?(y/n)"<<endl;
cin>>ch;
}
}while(ch!='n' && ch!='N');
return 0;
}
just a thought but in this code isn't there like a 1% chance that (age) will equal (guess) even before the user inputs an age?
edit:use infinitycounters solution
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int main()
{
srand(time(0));
int age = rand() % 100;
char ch;
int guess = 0;
do
{
cout <<"Guess an age between 1-100:";
cin >>guess;
if (guess == age)
{
cout <<"You guessed the right age!"<<endl;
break;
}
elseif (guess != age)
{
cout <<"Sorry, you guessed the wrong age. Do you want to try again?(y/n)"<<endl;
cin>>ch;
}
}while(ch=='y' || ch=='Y');
return 0;
}