while循环中的条件语句

时间:2012-04-22 19:41:14

标签: c++ conditional

我一定错过了什么。我正在练习学习c ++,并询问如果用户输入c,p,t或g字符然后继续,否则重新请求提示,所以我写了这个:

#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;
}

这不起作用,即使按下任一个正确的字符,我得到的是提示重新请求它。

但是,如果我改变这一行:

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

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

为什么?我的理解是“OR”语句应该正常,因为其中一个测试是正确的。

2 个答案:

答案 0 :(得分:6)

  

为什么?我的理解是“OR”语句应该正常,因为其中一个测试是正确的。

完全。总有其中一个测试通过。角色不是'c',也不是'p'。它不能同时为'c''p'。因此条件总是正确的,导致无限循环。

带连词的替代条件有效,因为只要ch等于其中一个选项,它就是假的:其中一个不等式是假的,因此整个条件都是假的。

答案 1 :(得分:3)

  

我的理解是“OR”语句应该正常,因为其中一个测试是正确的。

好吧,你可以使用||,但表达式必须是:

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

通过应用De Morgan's law,上述内容简化为:

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