【问题标题】:Why are my or operators not working as intended?为什么我的或操作员没有按预期工作?
【发布时间】:2020-08-26 05:07:00
【问题描述】:

无论输入如何,我的 if 语句都会受到影响。我无法理解为什么。代码如下:

void Novice::selection()
{
    char selection, shift;
    cout << "Please select a section to run: A - Home Row, B - Bottom Row, C - Top Row, D - Pointer Fingers, E - Right Pinky;" << endl;
    cin >> selection; 
    selection = toupper(selection);
    if (selection != 'A' || 'B' || 'C' || 'D' || 'E') {
        cout << "Invalid Input.  Please select again" << endl;
        cin >> selection; 
    }
    if (selection == 'A' || 'B' || 'C') {
        cout << "you're here" << endl;
    }

如果输入是'A',则触发第一个if语句,如果我再放入A,第二个if语句也会触发。任何帮助将不胜感激。

【问题讨论】:

标签: c++ operators


【解决方案1】:

这不是 C++ 中逻辑运算符的工作方式。要与多个值进行比较,您需要执行以下操作:

 if (selection == 'A' || selection == 'B' || selection == 'C') {
   // ...
}

请注意,您的第一个 if 不正确,即使您使用了上面的修复程序。如果您检查一个值是否不等于其他几个值,这将始终为真。这种情况可能需要类似于:

if (selection != 'A' && selection != 'B' && 
    selection != 'C' && selection !=  'D' && selection != 'E') {
  // ...
}

或者,对于第一个if 条件,您可以使用switch 语句,如下所示:

switch ( selection )
{
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
    break;
default:
    cout << "Invalid Input.  Please select again" << endl;
    cin >> selection;
}

【讨论】:

  • 或者干脆使用switch声明。
  • @AndreasWenzel 不确定switch 实际上是否更适合 OP 的示例。
  • 虽然对纠正这个问题不是很有用:if (selection != 'A' || 'B' || 'C' || 'D' || 'E')(需要使用&amp;&amp;)。
  • 没错,为此添加了解释。
  • 不用担心,很乐意提供帮助 :) 尽可能考虑accepting 的答案。另外,请拨打tour,您将获得一个徽章:)
猜你喜欢
  • 1970-01-01
  • 2020-02-29
  • 2019-08-28
  • 2014-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-04
  • 2021-01-03
相关资源
最近更新 更多