Getting an infinite loop, not sure why

[I am using Windows 7 and Visual Studio 2010. If this question should be posted in another topic, let me know :) Thank you.]

The objective of the program is to generate a random number between 1 and 20. The user makes a guess and the program plays the hot and cold game until the user guesses the number correctly. The program also keeps count of how many guesses the user had to make and displays the total once the user guesses correctly.

Once my program starts to run, the phrase "Too high. Try again." (or "Too low. Try again." depending on what number I guess) is outputted infinitely.

But I cannot tell where in my program I've created an infinite loop.

The compile/build did not find any syntax errors.

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
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
	
	int number, y = 6;
	unsigned seed = time(0);
	srand (seed);

	y = 1 + rand() % 20;
	
	int counter = 1;

	cout << "Please enter a number between 1 and 20. ";
	cin >> number;
	
	while (number != y)

		{
		 	if (number < y)
			cout << "Too low. Try again.";

			else if (number > y)
			cout << "Too high. Try again.";

			else
			cout << "Invalid entry. You must guess a number between 1 and 20. Try again.";
			counter++;
		}
	        
	cout << "That is correct!" << endl;
	cout << "You guessed " << counter << " times." << endl;

	return 0;
}
Your input is outside of the loop so the 'number' variable is never actually altered. Your user doesn't actually get another change to guess. Move the cin command to inside the loop (or add another one in there).
Last edited on
Of course ypur program is incorrect.
You do not change the value of variable number in the while-loop. So it is always the same.
Also there is no need to initialize y with 6 because below you assign it a new random value.
Thank you very much.


(Also, I apologize for the y=6, that was something I was using to try to find out where the problem was coming from and I just forgot to change it back).
Last edited on
Topic archived. No new replies allowed.