First program, need help

so i was trying to make a program that begs the user to pick a number.the program will ask the user "pick a number" up to 10 times and then exit unless the user picks the number 5.

code looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main()
{
	
     while (i < 10) 
	 {
           ++i;

	 cout << "pick a number" << endl;
	 cin >> UserNumber;

	 if (UserNumber = 5)
	 {
		 cout << "guessed it" << endl;
		 exit;
	 }
}
}


what happens is that the if statement keeps repeating over and over even though UserNumber does not = 5 anyone have an idea? :(
Last edited on
I'm not even sure how that compiles since I don't see where you defined your variables. I'm assuming you created them as globals and they look like this:
1
2
int i = 0;
int UserNumber;


As for your while loop not terminating, I'd suggest to do one of two things:
1) replace exit with break. This will break out of the while loop.

2) set i to 10, this will cause the loop to terminate as well, but effectively changes the value of i.

Also, you're missing the return statement for main.
yes, here is the whole code
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
#include <iostream>
using namespace std;
int UserNumber;
int i = 0;


int main()
{
	
     while (i < 10) 
	 {
		 ++i;
	 cout << i << endl;
	 cout << "pick a number" << endl;
	 cin >> UserNumber;

	 if (UserNumber = 5)
	 {
		 cout << "guessed it" << endl;
		 break;
	 }
}
return 0;
}



i changed exit to break but the problem still persist. The if statement keeps triggering even though UserNumber does not equal 5

for exampel if i compile the program and write an 8 the if statement triggers and i get "you guessed it" and the program exit
Last edited on
= Used to directly assign values.
== Used to check comparison between 2 variables.

Change line 17 to if (UserNumber == 5) and it should do what you want.
I must have been sleep replying. I didn't even read the question correctly, nor did I realize the assignment operator instead of a conditional operator. Regardless, break is better to use than exit.

James is correct with the == though.
works great now, thanks guys :>
Topic archived. No new replies allowed.