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;
}
With this statement:
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 seeadd
as the valuenull
and that is not equal to whatever the user inputs.You want to assign a value to it:
And all other strings the same.
And to compare std::string:
Another way to do it, is just to check it directly with a constant string: