在C++中遇到'while'循环时遇到问题

Bru*_*cky 1 c++ while-loop

我开始用C++构建一个非常简单的计算器版本.我们的想法是只用两个数字执行基本操作,然后循环回来,这样用户就可以进行新的计算.

该程序如下所示:

#include<iostream>
#include<string>
#include"mathOperations.h"
using namespace std;

int main()
{
  int x, y;
  string operation;
  string repeat = "y";

  while (repeat == "y" or "Y")
  {
    cout << "Welcome! This is a raw version of a calculator - only use two numbers." << endl;
    cin >> x >> operation >> y;

    if (operation == "+")
    {
      cout << "Result: " << add(x, y) << endl;
    }
    else if (operation == "-")
    {
      cout << "Result: " << subtract(x, y) << endl;
    }
    else if (operation == "*")
    {
      cout << "Result: " << multiply(x, y) << endl;
    }
    else if (operation == "/")
    {
      cout << "Result: " << divide(x, y) << endl;
    }
    else
    {
      cout << "This is not a valid sign. Please choose another one!" << endl;
    }

    cout << "Wanna go again? Type 'y' or 'n'." << endl;
    cin >> repeat;

    if (repeat == "n" or "N")
    {
      cout << "Alright, have a nice day!" << endl;
      break;
    }
  }
}

int add(int x, int y)
{
  return x + y;
}

int subtract(int x, int y)
{
  return x - y;
}

int multiply(int x, int y)
{
  return x * y;
}

int divide(int x, int y)
{
  return x / y;
}
Run Code Online (Sandbox Code Playgroud)

注意:有一个'mathOperations.h'文件,其中我已经使用了所有函数的前向声明.

问题是每当我输入'y'使其循环时,它只是输出以下'if'语句并突破循环并且程序结束.我无法弄清楚为什么会发生这种情况,因为如果输入'n','if'语句只能运行.

vso*_*tco 7

repeat == "n" or "N"
Run Code Online (Sandbox Code Playgroud)

评估为

(repeat == "n") || "N"
Run Code Online (Sandbox Code Playgroud)

请参阅C++运算符优先级.

第一个repeat == "n"求值truefalse取决于你的输入,但OR的第二个子句,即"N"总是求值为,true因为它是一个衰减到非零const char*指针的字符串文字,而在C或C++中,所有非零都是隐式转换的到true.因此,您的OR子句始终是true,这意味着if将始终执行该块.

如评论中所述,您需要这样做

if(repeat == "n" || repeat == "N") {...}
Run Code Online (Sandbox Code Playgroud)

与第一个while条件相似.