Basic Calculator Solution

So I have recently started studying C++ and my tutor had given us assignments to make a command line calculator.

The following code is a basic calculator that I extended for more options. I created a string called 'formula' and added a function to it but as soon as it gets to the function it is ignored and returns 0.

Also, if you could show me another alternative to shorten down the code because I feel as if the if statements are being written down in an unnecessary fashion that could be written in a more suitable alternative.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <string>
using namespace std;

int main(){
    
    int firstnumber;
    int secondnumber;
    string formula;
    
    cout << "Input the first number:\n";
    cin >> firstnumber;
    cout << "\n";
    
    cout << "Input the second number:\n";
    cin >> secondnumber;
    cout << "\n";
    
    cout << "Choose the sum: *, /, +, -\n";

// Program stops and returns 0 at this point.

    getline(cin, formula);
    
    if (formula == "*"){
        cout << "The answer is: " << firstnumber*secondnumber << "\n";
    };
    if (formula == "/"){
        cout << "The answer is: " << firstnumber/secondnumber << "\n";
    };
    if (formula == "+"){
        cout << "The answer is: " << firstnumber+secondnumber << "\n";
    };
    if (formula == "-"){
        cout << "The answer is: " << firstnumber-secondnumber << "\n";
    };
    cout << endl;
    
    return 0;
}
Try to write "cin >> formula" instead getline(cin,formula)
closed account (iAk3T05o)
Switch, char operation (+, -, /, *) and cin it all one line and you will have less code
Thanks alot @AnaMota, your suggestion seemed to have worked.

Also, @Nathan2222 how might I go about doing that?
You could always do it something like this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <fstream>
#include<string>
using namespace std;

int doMath(int x,int y,string operation)
{
    if (operation=="+")
        return x+y;
    else if (operation=="-")
        return x-y;
    else if (operation=="*")
        return x*y;
    else
        return x/y;
}

int main()
{
    int firstNum,secondNum;
    string formula;

    for (int i=1;i<3;i++)
    {
        cout<<"Please enter the "<<((i==1) ? "1st" : "2nd")<<" value: ";
        if (i==1)
            cin>>firstNum;
        else
            cin>>secondNum;
    }
    cout<<"Please choose the operation to be performed (+,-,*,/): ";
    cin>>formula;
    cout<<"The answer is: "<<doMath(firstNum,secondNum,formula);
}

If you're wondering, the cout statement on line 25 acts as an if/else statement to output 1st or 2nd as applicable. You can always cut down on duplicate output code this way, and a good example is the various output statements in your code, which are all the same other than the math being performed.
Last edited on
closed account (iAk3T05o)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int first_number = 0;
int second_number = 0;
char formula = ' ';

std::cout <<"Enter operation: ";
 
std::cin >> first_number >> formula >> second_number; //get first number, formula(+, -, /, *) and second number

switch (formula) // if formula . . .
{
case '+': // . . . == '+'
std::cout << first_number+second_number;

//case other formula
}
return 0;

Idk about what Nathan said, but you really want only one character to go into formula - so why get whole string?
1
2
3
4
5
6
char formula;
//code...
if( formula == '*') //Mind single quotation mark, not double! 
{
     //do something...
}


Also, we're in C++; you don't have to write '\n', where you can use std::endl :)

As for getting input, use cin as AnaMota suggested.

Cheers!
Last edited on
Also, take a look at this: (Your code)
1
2
3
4
5
6
7
8
9
10
11
12
if (formula == "*"){
        cout << "The answer is: " << firstnumber*secondnumber << "\n";
    };
    if (formula == "/"){
        cout << "The answer is: " << firstnumber/secondnumber << "\n";
    };
    if (formula == "+"){
        cout << "The answer is: " << firstnumber+secondnumber << "\n";
    };
    if (formula == "-"){
        cout << "The answer is: " << firstnumber-secondnumber << "\n";
    };

vs
1
2
    cout << "The answer is: " << ((formula=="+") ? firstnumber+secondnumber : (formula=="-") ? firstnumber-secondnumber : 
                                  (formula=="*") ? firstnumber*secondnumber : firstnumber/secondnumber)<<endl;

Both do the same thing, but the second example takes away alot of the redundancy in the original code. If you're not comfortable with using ternary, or conditional, operators like this, you can still reduce the amount of code involved here like below.
1
2
3
4
5
6
7
8
9
10
cout << "The answer is: ";
if (formula == "*")
    cout << firstnumber*secondnumber;
else if (formula == "/")
    cout << firstnumber/secondnumber;
else if (formula == "+")
    cout <<firstnumber+secondnumber;
else
    cout << firstnumber-secondnumber;
cout<<endl;

As each if statement involved only one line, there's no need for enclosing brackets, and the output common to each scenario can be outputted separate from the if statement, which is only used to change the desired portion of the output. Of course, in this case any input that was not a *,/, or + would be considered a -, but we could always include the input line for formula within a loop until it was one of the four symbols, and have it keep asking until it gets one of them.

I'd prefer to do it more like this, myself.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <fstream>
#include<string>
using namespace std;

float doMath(float x,float y,string operation)
{
    if (operation=="+")
        return x+y;
    else if (operation=="-")
        return x-y;
    else if (operation=="*")
        return x*y;
    else
        return x/y;
}

int main()
{
    float firstNum,secondNum;
    string formula=" ";

    for (int i=1; i<3; i++)
    {
        cout<<"Please enter the "<<((i==1) ? "1st" : "2nd")<<" value: ";
        if (i==1)
            cin>>firstNum;
        else
            cin>>secondNum;
    }
    cin.ignore();//clears buffer to avoid unneeded repetition of loop
    while (formula!="+" && formula!="-" && formula!="*" && formula!="/")
    {
        cout<<"Please choose the operation to be performed (+,-,*,/): ";
        cin>>formula;
    }
    cout<<"The answer is: "<<doMath(firstNum,secondNum,formula);
}

Please enter the 1st value: 4
Please enter the 2nd value: 5
Please choose the operation to be performed (+,-,*,/): 6
Please choose the operation to be performed (+,-,*,/): /
The answer is: 0.8
Last edited on
As per usual, everyone forgets to check for divide by zero. Have a look at some other posts on this forum for how to do it with floating point numbers.

Because I am relatively old & grumpy :+), I really dislike these constructs:

while (formula!="+" && formula!="-" && formula!="*" && formula!="/")

I find them error prone, non scalable & just plain ugly !! IMO a switch statement is much better - it might be more code, but it has it advantages.

Anyway, hope all is going well for everyone at their end :)
Good point, IdeasMan. I had forgotten about the check for zero when dividing. I'm personally a fan of ternary operators for condensing simple stuff like this as opposed to using switch or chaining if/else statements. It's really only applicable when assigning or checking a small number of values, though. I found it particularly useful in my tic tac toe program, reducing multiple lines of code down to a few lines. When the values are entered correctly, and they are correctly structured and commented, I don't see a problem, but I can see how it could potentially be one with larger structures.

Personally, I would have used an int for operation selection, but the OP had it set up this way initially and my modifications were more about the way the output was achieved than it was about being the ultimate solution.
I was trying to point out how much of the redundancy could be cut down because the OP had asked how it could be reduced. But I'm curious, how do you control a loop using a switch statement? I may have developed preferences and opinions, but I'm always willing to learn more, because there's much I still don't know. Sometimes I've seen loops used in odd ways I didn't understand, such as employing multiple counters or even functions.
Last edited on
1
2
3
if (formula == "*"){
        cout << "The answer is: " << firstnumber*secondnumber << "\n";
    };    //I dont think the semi colon ought to be there I dont know sorry if I am wrong I am a beginner 
@CplusplusAcolyte

The switch acts like a menu, so one can have a quit option which sets a boolean variable - the loop terminates when it is true. Each case should probably call a function to do it's work, unless it's trivial. Also a default case to catch bad input.

Here is an example I prepared earlier:

http://www.cplusplus.com/forum/beginner/99203/#msg534078


I agree, ternary operators are great for simple if-then-else, but a switch in case is much better than your while condition, IMO because of the scalability, simplicity & maintainability. For these reasons I would rather have more code in a switch, rather than a nasty one liner.

With scalability, how would one code a calculator that had 20 or even 50 functions, using such a while condition?

One could use a char or an unsigned integer type (maybe even an unsigned short) for the menu selection - what ever squeals your wheels.

Have fun.
Thanks for the clarification.
Topic archived. No new replies allowed.