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.
#include <iostream>
#include <fstream>
#include<string>
usingnamespace std;
int doMath(int x,int y,string operation)
{
if (operation=="+")
return x+y;
elseif (operation=="-")
return x-y;
elseif (operation=="*")
return x*y;
elsereturn 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.
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;
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.
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.
#include <iostream>
#include <fstream>
#include<string>
usingnamespace std;
float doMath(float x,float y,string operation)
{
if (operation=="+")
return x+y;
elseif (operation=="-")
return x-y;
elseif (operation=="*")
return x*y;
elsereturn 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
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.
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
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.
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 unsignedshort) for the menu selection - what ever squeals your wheels.