While loops, Program not ending.

Hello everyone, this is my first post. I'm having trouble doing while loops. I've lost a LOT of points in my programming class because of this and I do not want to fail.

If you guess the right number and try to input anything the program just repeats "Do you want to play again? Y or N"

Also if you enter any character before guessing the right number the program forever repeats "Guess a number between 1 and 10: "

Please help.

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <ctime>

using namespace std;

int main()
{

	srand(static_cast<unsigned int>(time(0)));

	int count = 1;
	char ans;


	while (toupper(ans = 'Y'))
	{
		int num = rand() % 10 + 1;
		int guess;
		cout << "Guess a number between 1 and 10: " << endl;
		cin >> guess;

		while (guess != num)
		{

			count++;

			cout << "Guess a number between 1 and 10: " << endl;
			cin >> guess;
		}

		while (guess = num)
		{
			cout << "It took " << count << " Guesses to guess correctly" << endl;
			cout << endl << "Do you want to play again?  Y or N" << endl;
			cin >> ans;
		}

	}


	return 0;

}
Last edited on
closed account (48T7M4Gy)
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
30
31
32
33
34
35
36
#include <iostream>
#include <ctime>

using namespace std;

int main()
{

	srand(static_cast<unsigned int>(time(0)));

	int count = 0, guess = 0, num;
	char ans = 'Y';


	while (toupper(ans) == 'Y')
	{
		count = 1;
		num = rand() % 10 + 1;
		
		cout << "Guess a number between 1 and 10: " << endl;
		cin >> guess;

		while (guess != num)
		{
		    count++;

			cout << "Guess a number between 1 and 10: " << endl;
			cin >> guess;
		}
		
		cout << "It took " << count << " Guesses to guess correctly" << endl;
		cout << endl << "Do you want to play again?  Y or N" << endl;
		cin >> ans;
	}
	return 0;
}
Thank you kemort! I see my mistakes now.
Topic archived. No new replies allowed.