简体   繁体   中英

conditional statement in while loop

I must have missed something. I'm doing an exercise to learn c++ and it asks that if a user inputs either c,p,t or g character then carry on, otherwise re-request prompt, so I wrote this:

#include <iostream>
#include <cstring>
#include <string>

using namespace std;

int main(void){
  cout << "Please enter one of the following choices:" << endl;
  cout << "c) carnivore\t\t\tp) pianist\n";
  cout << "t) tree\t\t\t\tg) game\n";
  char ch;
  do{
    cout << "Please enter a c, p, t, or g: ";
    cin >> ch;
    cout << "\"" << ch << "\"" << endl;
  }while(ch != 'c' || ch != 'p' || ch != 't' || ch != 'g');

  cout << "End" << endl;

  cin.clear();
  cin.ignore();
  cin.get();

  return 0;
}

This does not work and all I get is the prompt re-requesting it even when pressing either of the correct characters.

However if I change this line:

while(ch != 'c' || ch != 'p' || ch != 't' || ch != 'g');

to

while(ch != 'c' && ch != 'p' && ch != 't' && ch != 'g');

why is that? My understanding is that the "OR" statement should work as one of the tests is correct.

why is that? My understanding is that the "OR" statement should work as one of the tests is correct.

Exactly. There is always one of the tests that passes. A character will either be not 'c' , or not 'p' . It can't be both 'c' and 'p' . So the condition is always true, leading to an infinite loop.

The alternative condition with the conjunctions works because it is false as soon as ch is equal to one of the alternatives: one of the inequalities is false, and thus the whole condition is false.

My understanding is that the "OR" statement should work as one of the tests is correct.

Well, you could use || , but the expression would have to be:

while(!(ch == 'c' || ch == 'p' || ch == 't' || ch == 'g'));

By applying the De Morgan's law , the above simplifies to:

while(ch != 'c' && ch != 'p' && ch != 't' && ch != 'g');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM