if statement - chained if-else not working (C++) -
i'm beginner , having trouble chained if-else statement. when run program, , enter item select, outputs "invalid entry.". why isn't executing proper function when equal in 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 calculator.\n\n"; cout << "please enter 2 numbers.\n\n"; int a; int b; cin >> >> b; cout << "what these numbers?\nhere 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 statement:
string add;
you creating string variable name add
, there not yet value assigned it. when compare variable user input, program see add
value null
, not equal whatever user inputs.
you want assign value it:
string add = "add";
and other strings same.
and compare std::string:
if(choice == add)
another way it, check directly constant string:
if(choice == "add"){ //do }else if(choice == "subtract") //do else
Comments
Post a Comment