While loop for guessing a persons age

Write a C++ program that uses a while loop to guess a persons age, ask the user if they want to try again if no end the loop. Of course if they guess it the loop also ends

First we need to generate a random age to be guessed? So,

// Generate random age to be guessed
srand(time(0));
int age = rand() % 110 //I am assuming not many have lived this long


while (guess != age)
{
//Prompt the user to guess an age
cout << "Guess an age, 1-110: ";
int guess;
cin >> guess

if (guess == age)
cout << "You guessed the correct age!" << endl;
else if (guess != age)
cout << Sorry, you guessed the wrong age, would you like to take another guess?";

This is where I am stuck. If we end the loop here then how will our user be able to guess again? Thanks




bump
That is the point of the loop, the loop will continue until the condition is met. One thing you need to look at is cin.clear() and cin.ignore() otherwise the program will not handle invalid input very well.
So you are saying the loop is correct if I end it there(other than the stuff you mentioned i should take a look at)?

If the user enters an invalid input( >110<1?) won't the program just output "Sorry, you guessed the wrong age, would you like to take another guess?" If I am wrong can you explain why? Thanks.
To illustrate how a loop works.

1
2
3
4
5
6
7
8
unsigned i = 1;

while (i < 10) {
 cout << "i is currently " << i << endl;
 i++;
}

cout << "Wow.. i counted from 1 - 9" << endl;


If the person guesses right then you want to exit the loop then, use the break; keyword to do this.
// Generate random age to be guessed
srand(time(0));
int age = rand() % 110 //I am assuming not many have lived this long


while (guess != age)
{
//Prompt the user to guess an age
cout << "Guess an age, 1-110: ";
int guess;
cin >> guess

if (guess == age)
cout << "You guessed the correct age!";
break;

else if (guess != age)
cout << Sorry, you guessed the wrong age, would you like to take another guess?" << endl;
}

I shouldn't include a break after the second output(sorry you guessed the wrong age...") because I do not want the loop to exit if the person guesses the wrong age.

At the same time I don't want to repeat the same loop, I want the user to first answer if he would like to guess another age, and if the user answers yes, the loop should repeat again, however if he gives up the loop will exit as well. How would I go about approaching this?
Topic archived. No new replies allowed.