#include <iostream>
int main()
{
usingnamespace 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;
}
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.