else if problem.

I just learned if statements like 3 days ago and was just messing around and came up with this.But than when i type 2 it said thank you or and other number..it should only say thank you for number 1 please help.thanks

I know i can do it with switch statements but i only wanted to use if statements so i can learn
Thanks

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>
using namespace std;

int main()
{
	int val;
	cout << "Is Captain Awesome? \nYes = 1 \nNo = 2" << endl;
	cin >> val;

	if (val = 1)
	{
		cout << "\nOh thank you. :) \n" << endl;
	}
	else if (val = 2)
	{	
		cout << "\nOk you ask for it. :P \n" << endl;
	}
	else
	{
		cout << "Only 1 to 2" << endl;
	}
	
	system("PAUSE");
	return 0;
}
line 10:

 
if (val ==1)


line 14:
 
if (val==2)
                 
Last edited on
You're using the assignment operator (=) in your if-statement when instead you should use the equality operator (==).

Your statement if (val = 1) and other statements like this should instead read:

if (val == 1)
You want to check equality, not assign val a new value.

*EDIT: Hah people all jumped on this at the same time.
Last edited on
This is a mistake a lot of people make when first using if statements. The reason that it always says "Oh thank you." is that you're using = instead of ==. = assigns a value to a variable so your first condition ( if (val = 1) ) will always be executed. == compares two values to see if they are equal. change if (val = 1) and else if (val = 2) to if (val == 1) and else if (val == 2).
I must say that the program works, however, with the exception of the else statement, that in case you are using (=) instead of (==) returns random results.
Oh .yes loads of ppl have said to use ==..i just forgot ..gota keep that in mind thanks all ..so much
I must say that the program works, however, with the exception of the else statement, that in case you are using (=) instead of (==) returns random results.

I'm not quite sure what you're trying to say. Having:

if (val = 1)

does not cause any random results. The statement val = 1 always evaluates to 1, and since 1 is non-zero, it is always considered true in a conditional statement. Therefore, the first conditional block in the posted code will always execute, and the other blocks (the else if and the else) will never execute.

Nothing random about it at all. It's well-defined behaviour.
Last edited on
Topic archived. No new replies allowed.