Reputation:
do
{
cout << "Car is coming ... " << "[P]ay or [N]ot?" << endl;
ch=getch();
} while ( ch !='q' || ch != 'Q');
Why will the code on top not work while the code below does? I tried it with parenthesis around each statement in numerous ways and the compiler would pop an error every time until I regrouped them as I did below. I'm just wondering why it does this.
do
{
cout << "Car is coming ... " << "[P]ay or [N]ot?" << endl;
ch=getch();
} while ( !(ch=='q' || ch=='Q') );
I'm using Visual Studio 2008 as my compiler; x86 architecture.
Upvotes: 3
Views: 562
Reputation: 19392
When inverting all your logic using '!', you did right by reversing the conditional operators "==" to "!=", but you forgot to reverse the logical operators "||" to "&&". Thus, this should be correct:
while (ch!='q' && ch!='Q');
I use C#, so while code above will work, I would have used this instead as it is easier to read:
while (ch.ToUpper() != 'Q');
Upvotes: 0
Reputation: 20609
You've got the logic backwards, that's my negating it works. By DeMirgan's laws, !(ch == 'Q' || ch == 'q')
is the same as ch != 'Q' && ch != 'q'
.
Since a if it cannot be both little q
and big Q
at the same time, while (ch != 'Q' || ch != 'q')
doesn't make sense because if it is 'Q' then it won't be 'q', and vice versa.
Upvotes: 0
Reputation: 754715
The problem is your boolean logic is off and the two while
conditions are not the same.
The Top will return true for every single character possible. The bottom will return true for every character except 'q' and 'Q'
Upvotes: 2
Reputation: 12202
!(ch=='q' || ch=='Q')
is equivalent to ch!='q' && ch!='Q'
. See also De Morgan's laws.
Upvotes: 0
Reputation: 272497
(ch != 'q' || ch != 'Q')
is always true: "ch
is not equal to 'q'
or ch
is not equal to 'Q'
".
Upvotes: 3
Reputation: 30996
I think you want this in your first example:
ch !='q' && ch != 'Q'
You want that the input is not q
AND not Q
.
Upvotes: 0