Do During Loop Question

do 
{
  cout << "Car is coming ... " << "[P]ay or [N]ot?" << endl;
  ch=getch();
} while ( ch !='q' || ch != 'Q');

Why doesn't the code above work while the code is below? I tried it with parentheses around each statement in various ways, and the compiler came up with an error every time until I regrouped them, as I did below. I'm just wondering why this is happening.

do 
{
  cout << "Car is coming ... " << "[P]ay or [N]ot?" << endl;
  ch=getch();
} while ( !(ch=='q' || ch=='Q') );

I use Visual Studio 2008 as my compiler; x86.

+3
source share
7 answers

Learn the laws of De Morgan

(not A) or (not B)

does not match

no (A or B).

+16
source

(ch != 'q' || ch != 'Q')always true: " chnot equal 'q'or chnot equal 'q'."

+3
source

, , while .

  • : "q" "Q"
  • : ('q' 'Q')

Top true . true , "q" "Q"

+2

, :

ch !='q' && ch != 'Q'

, q q.

0

!(ch=='q' || ch=='Q') ch!='q' && ch!='Q'. . .

0

, . !(ch == 'Q' || ch == 'q') ch != 'Q' && ch != 'q'.

a, little q, big Q, while (ch != 'Q' || ch != 'q') , "Q", "q", .

0

When inverting all your logic with "!" you did the right thing by changing the conditional statements "==" to "! =", but you forgot to change the logical operators "||" on the "& &". So this should be correct:

while (ch!='q' && ch!='Q');

I am using C #, therefore, while the code above will work, I would use this instead, since it is easier to read:

while (ch.ToUpper() != 'Q');
0
source

All Articles