Bruncky
Bruncky

Reputation: 117

Having trouble with a 'while' loop in C++

I started building a very simple version of a calculator in C++. The idea is to perform basic operations with only two numbers and then loop back so the user can make a new calculation.

The program looks like this:

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

NOTE: There is a 'mathOperations.h' file in which I have made forward declarations of all functions used.

The problem is that whenever I type in 'y' to make it loop, it simply outputs the following 'if' statement and breaks out of the loop and the program finishes. I couldn't quite figure out why this is happening, since the 'if' statement is only supposed to run if I type in 'n'.

Upvotes: 1

Views: 104

Answers (2)

Chriskt
Chriskt

Reputation: 87

Nice code! I try using "||" in place of your "or" in your if statements. Might want to refresh your knowledge with C++ short-circuiting of booleans.

Upvotes: 1

vsoftco
vsoftco

Reputation: 56577

repeat == "n" or "N"

evaluates to

(repeat == "n") || "N"

see the C++ operator precedence.

The first repeat == "n" evaluates to true or false depending on your input, but the second clause of the OR, i.e. "N", always evaluates to true because it is a string literal that decays to a non-zero const char* pointer, and in C or C++ everything non-zero is implicitly converted to true. So your OR clause is always true, which implies that the if block will always be executed.

As mentioned in the comments, you need to do

if(repeat == "n" || repeat == "N") {...}

Similarly with the first while condition.

Upvotes: 7

Related Questions