chained if-else not working (C++)

196 views Asked by At

I'm a beginner and am having trouble with my chained if-else statement. When I run the program, and I enter which item I select, it always outputs "Invalid entry.". Why isn't it executing the proper function when it is equal to it in the if-statement?

Thank you,

Don

#include <iostream>
using namespace std;

int sum(int int1, int int2 ){

    return int1 + int2;

}

int difference( int int1, int int2 ){

    return int1 - int2;

}

int product( int int1, int int2 ){

    return int1 * int2;

}

int quotient( int int1, int int2 ){

    return int1 / int2;

}

int main(){

cout << "\nWelcome to the calculator.\n\n";
cout << "Please enter two numbers.\n\n";

int a;
int b;
cin >> a >> b;

cout << "What would you like to do with these numbers?\nHere are your options: add, subtract, multiply, or divide.\n\n";

string add;
string subtract;
string multiply;
string divide;

string choice;
cin >> choice;


if( choice == add )
    cout << sum( a, b );
else if ( choice == subtract )
    cout << difference( a, b );
else if ( choice == multiply )
    cout << product( a, b );
else if ( choice == divide )
    cout << quotient( a, b );
else 
    cout << "Invalid entry.\n"; 

return 0;

}
1

There are 1 answers

2
moffeltje On BEST ANSWER

With this statement:

string add;

You are creating a string variable with the name add, but there is not yet a value assigned to it. So when you compare the variable with the user input, the program will see add as the value null and that is not equal to whatever the user inputs.

You want to assign a value to it:

string add = "add";

And all other strings the same.

And to compare std::string:

if(choice == add)

Another way to do it, is just to check it directly with a constant string:

if(choice == "add"){
  //do something
}else if(choice == "subtract") 
  //do something else