Ending while loop with user input

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  #include <iostream>
#include <cstdlib>
#include <ctime>
using namespace 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;
		else if (guess != age)
			cout <<"Sorry, you guessed the wrong age. Do you want to try again?"<<endl;
			
}
return 0;
}
Try this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace 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;
                }
		else if (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;
}
Last edited on
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
Last edited on
@InfinityCounter,
I think you've made a mistake in the end of the do-while loop.
while(ch!='y' || ch!='Y');
I assume what you meant to write is this:



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace 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;
	    }
		else if (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;
}
@Jacobhaha, thanks.
Topic archived. No new replies allowed.