IF Statement Issue

Hi Guys,

I find that with the below code, the following line is appearing even when either a,b,c,d or q is selected.

 
cout << "Please enter a), b), c), d) or q)" << endl;


Any ideas why?

Thanks for your help guys!

Kind Regards,

Giri

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
45
46
47
48
49
50
51
52
#include <iostream>


int main()
{
	using namespace std;

	cout << "Please enter one of the following choices:" << endl;
	cout << "a) carnivore        b) pianist" << endl;
	cout << "c) tree             d) game" << endl;
	cout << "q) quit" << endl;

	char choice;

	while ( cin >> choice)
	{
		if (choice != 'a' || 'b' || 'c'|| 'd' || 'q') 
			{
				cin.clear();
					while (cin.get() != '\n')
						continue;
				cout << "Please enter a), b), c), d) or q)" << endl;  // This line is always appearing even when
			}														  // a,b,c or d is not typed.
	
		
		
		switch(choice)
		{
			case 'a': cout << "I am a carnivore" << endl;
					  break;

			case 'b': cout << "I am a pianist" << endl;
					  break;

			case 'c': cout << "I am a tree" << endl;
					  break;

			case 'd': cout << "I am a game" << endl;
					  break;

			case 'q': cout << "Time to go! Goodbye!" << endl;
		}
	}
	
	
	cin.get();
	
	return 0;

}

 
if(choice != 'a' && choice != 'b' && ...)
To expand on Calig's answer, this

(choice != 'a' || 'b' || 'c'|| 'd' || 'q')

ALWAYS evaluates to true.
I think you are having trouble with the condition ,try this . . .
 
if(choice !='a' || choice !='b' || choice !='c' || choice !='d' || choice !='q' )
Last edited on
if(choice !='a' || choice !='b' || choice !='c' || choice !='d' || choice !='q' )

That also will ALWAYS come out as true.
Awesome! Thanks for the replies guys.

May I ask why my way did not work?

Thanks again!

Kind Regards,

Giri
First shorten the condition to (choice != 'a' || 'b' ) since the extra || do not affect the analysis.

Because of operator precedence the expression is evaluated as:

( choice != 'a' ) || ( 'b' )

The first condition may be true or false but the second condition ( 'b' ) will always evaluate to true and hence the whole OR expression will always be true. Why does ( 'b' ) evaluate to true? The char type is actually an integral type in C++ and any integral type when converted to a boolean evaluates to false for zero and true for any non-zero value. The ASCII value of 'b' is 98 and hence when converted to a boolean is true.

if(choice !='a' && choice !='b' && choice !='c' && choice !='d' && choice !='q' )

try this one,would it help?
Topic archived. No new replies allowed.