JayLav
JayLav

Reputation: 101

Basic calculator C++, there is no error but code only returns 0 regardless of the value

I'm fairly new to coding and I wanted to attempt a basic calculator after weeks of studying, however this code only returns the value of 0 regardless of the number or function input. I'm not sure what I'm doing wrong.

#include<iostream>    
using namespace std;

int main(){     
    int number;
    int secNumber;
    int sum;
    string function;
    string add;
    string subtract;
    string divide;
    string modulus;
    string multiply;

    cout << "what will be your first number?" << endl;      
    cin >> number;

    cout << "what will be your second number?" << endl;     
    cin >> secNumber;

    cout << "what would you like to do with these number?" << endl;     
    cin >> function;

    if (function==add)          
        sum = number + secNumber;           
    else if (function==subtract)            
        sum = number - secNumber;           
    else if(function== divide)          
        sum = number/secNumber;         
    else if(function== multiply)            
        sum = number*secNumber;         
    else if(function==modulus)          
        sum = number%secNumber;

    cout << "Your sum is "<<sum << endl;
    return sum;
}

Upvotes: 1

Views: 65

Answers (1)

Barry
Barry

Reputation: 302738

You're not initializing add, subtract, etc. Those strings are all empty. So regardless of what function you're entering, they're not going to compare equal against an empty string.

Instead, compare against string literals:

if (function == "add") {
    sum = number + secNumber;
}
else if (function == "subtract") {
    ...
}
...

It would also be helpful to add an error message at the end, in case the user enters an invalid function:

else {
    std::cout << "Unknown function " << function;
}

Upvotes: 3

Related Questions