-2

I am new to C++ (Coming from python). When I am comparing a string in an If statement it is always false.

#include <iostream>
#include <string>
using namespace std;
int main(){
    string op;
    int num1;
    int num2;
    cout << "Operator? ('+', '-', '*', '/' )" << endl;
    cin >> op;
    cout << "Number 1?" << endl;
    cin >> num1;
    cout << "Number 2?" << endl;
    cin >> num2;
    int result;
    cout << op << endl;
    if (op == "+"){
        int result = num1 + num2;
    }
    if (op == "-"){
        int result = num1 - num2;
    }
    if (op == "*"){
        int result = num1 * num2;
    }
    if (op == "/"){
        int result = num1 / num2;
    }
    else{
        cout << "Invalid Operator" << endl;
        return 0;
    }
    cout << "Result is " << result << endl;
}

When I feed it the inputs '+', '1', and '1', It prints '+', meaning it read the input. But then I expect it to give me 'The result is 2', but it prints "Invalid operator". What can i do to fix this?

Aman Raj
  • 239
  • 3
  • 15

5 Answers5

2

Seen this a few times recently. If you want to choose one of several alternative using if, then you write it like this

if ... else if ... else if ... else if ... else ...

Not like this (what you have written)

if ... if ... if ... if ... else ...

I know python is strange but I expect in this case it's exactly the same as C++.

Then you have the problem that you have five different result variables

int result;                    // first result variable
cout << op << endl;
if (op == +){
   int result = num1 + num2;   // second result variable
}

should be

int result;
cout << op << endl;
if (op == +) {
   result = num1 + num2;
}

etc. etc.

john
  • 85,011
  • 4
  • 57
  • 81
  • (`+1`) Would also be nice to suggest `switch() { case: }` as an alternative since it'd be suitable here and Python doesn't really have it – Aykhan Hagverdili Jul 06 '19 at 15:05
  • @Ayxan Please explain how you will compare a `std::string` with a switch/case. Give examples. – Lightness Races in Orbit Jul 06 '19 at 15:19
  • @LightnessRacesinOrbit There;s really no point to make the operators strings instead of characters. That's how – Aykhan Hagverdili Jul 06 '19 at 15:20
  • @Ayxan So you're actually suggesting the combination of switching to `char` _and_ switching to switch/case. You didn't say that before. See my comment to Aman. – Lightness Races in Orbit Jul 06 '19 at 15:21
  • 1
    This still doesn't fix the root of the problem is still not fixed. `+` still has no quotes. –  Jul 06 '19 at 15:51
  • Thank you, changing if to else if worked great. And to anyone saying i forgot quotation marks around +, I know that doesn't work, I tried it and forgot to change it back before asking the question – Gary Flermen Jul 06 '19 at 17:29
1

Since no one has offered a suitable answer in my opinion, the answer is basically a typo (I'm assuming, since you do it the right way the other times). The problem is this line right here:

if (op == +){

Honestly, I'm not sure what this does, but I can tell you it doesn't do what you expect. + is an actual C++ operator. Since it has nothing next to it on either side, I'm not exactly sure what this expression actually does. But again, it is not what you intend.

What you want is a quoted + sign:

if (op == "+"){

The difference with "+" is that "+" is a sting containing the character +, not an actual C++ operator. That's what you actually want. It will do what you expect, and won't always end up with "invalid operator".


One other thing before I go, it would be a disservice to you to to not mention that you actually have 2 bugs, even if you only are asking about the one. That is, as others have mentioned, you are creating another variable in another scope when you actually perform your operation:

int result;
cout << op << endl;
if (op == "+"){ // decided to use a fixed version of the if statement as an example
   int result = num1 + num2;
}

In C++, that's a gotch ya. The int in front of result in the second line creates a new variable called result. That new variable goes out of scope almost immediately. Thus, your result isn't saved at all, but instead you get uninitialized data.

The solution is relatively simple: just remove the int keyword in your second example:

result = num1 + num2;

Of course, you will need to do this on all of your operations, not just +.

  • You're right, I needed to remove the int signs, but the + was not the problem. I tried to get it to work by removing the quotation marks, and it didn't work, but i forgot to change it back before asking – Gary Flermen Jul 06 '19 at 17:30
  • Re: "containing the ASCII character +" -- maybe, **if** your compiler uses ASCII (which almost all do). But character codes are not restricted to ASCII, and in this case (as in most cases) the encoding is irrelevant; `"+"` is a string containing the character `'+'` is sufficient. – Pete Becker Jul 06 '19 at 17:33
  • @pete fair enough about ASCII. I'm still unfamiliar with UTF, so sometimes I forget that it is more commonly used than ASCII now days. As to `'+'` being sufficient, yes, it is, but why not use double quotes, especially since it's more consistent with the OP's style? –  Jul 06 '19 at 17:41
  • I was re-writing your comment, not recommending single quotes. But `op` should be a `char`, not a `std::string`, and then the comparisons should be against character constants like `'+'` and not strings like `"+"`. – Pete Becker Jul 06 '19 at 21:20
  • @pete again, I ask why? It's not making sense to me. I'm not understanding your logic. Could you be more explicit? –  Jul 07 '19 at 01:57
  • All I meant was that “`”+”` is a string containing the ASCII character +” should be replaced by “`”+”` is a string containing the character +”. – Pete Becker Jul 07 '19 at 02:25
  • @PeteBecker Got you, it clicked now. Thank you. I thought you were saying we shouldn't use double quotes, which I think makes no difference. –  Jul 07 '19 at 04:15
1

You have to use else if instead of if every time.

Here is the working code.

#include <iostream>
#include <string>
using namespace std;
int main(){
    string op;
    int num1;
    int num2;
    cout << "Operator? ('+', '-', '*', '/' )" << endl;
    cin >> op;
    cout << "Number 1?" << endl;
    cin >> num1;
    cout << "Number 2?" << endl;
    cin >> num2;
    int result;
    cout << op << endl;
    if (op == "+")
    {
         result = num1 + num2;
    }
    else if (op == "-")
    {
         result = num1 - num2;
    }
    else if (op == "*")
    {
         result = num1 * num2;
    }
    else if (op == "/")
    {
         result = num1 / num2;
    }
    else
    {
        cout << "Invalid Operator" << endl;
        return 0;
    }
    cout << "Result is " << result << endl;
}
Harsh Raj
  • 11
  • 5
0

As you are new to c++. Few suggestion here

  1. As you know c++ is statical typed . So you should know all data types of c++. Like when you are using single character you can use char insted of string
  2. You should not redifine variable every time you use.
#include <iostream>
#include <string>
using namespace std;
int main(){
    string op;
    int num1;
    int num2;
    cout << "Operator? ('+', '-', '*', '/' )" << endl;
    cin >> op;
    cout << "Number 1?" << endl;
    cin >> num1;
    cout << "Number 2?" << endl;
    cin >> num2;
    int result;
    cout << op << endl;
    if (op == "+"){
         result = num1 + num2;
    }
    else if (op == "-"){
         result = num1 - num2;
    }
    else if (op == "*"){
         result = num1 * num2;
    }
    else if (op == "/"){
         result = num1 / num2;
    }
    else{
        cout << "Invalid Operator" << endl;
        return 0;
    }
    cout << "Result is " << result << endl;
}

Aman Raj
  • 239
  • 3
  • 15
  • 1
    Static typing doesn't really have anything to do with this. Yes, you could choose to take your input into a `char`, but you'd be making more problems for yourself. How do you detect when someone illegally entered a multi-character input? How do you suck up the newline in the buffer? You're making more work for yourself. A string input here is perfectly reasonable. – Lightness Races in Orbit Jul 06 '19 at 15:17
  • Thanks for the char tip, but as Lightness pointed out, I couldn't detect multicharacter inputs. – Gary Flermen Jul 06 '19 at 17:32
0

Improved your Code. In this case, Comparing std::string was really not necessary. Have fun!

#include <iostream>

//using namespace std;

int main()
{
    char operation; 
    float num1, num2, result;
    std::cout << "Enter Operator (+,-,/,*) : ";
    std::cin >> operation;
    std::cout << "\nNumber 1 : ";
    std::cin >> num1;
    std::cout << "\nNumber 2 : ";
    std::cin >> num2;
    switch(operation)
    {
        case '+':
        result = num1 + num2;
        break;
        case '-':
        result = num1 - num2;
        break;
        case '/':
        result = num1 / num2;
        break;
        case '*':
        result = num1 * num2;
        break;
        default:
        result = num1 + num2; 
    }
    std::cout << "Result : " << result << std::endl;
}

https://im.ezgif.com/tmp/ezgif-1-76ceb4e91c2c.gif

Lynx
  • 147
  • 2
  • 8