In: Computer Science
TASK:
Using stack functions, write a program in C++ language that acts as a simple calculator, reading an infix algebraic expression with numbers and simple operations: +, -, *, / , (, and ). The program converts an infix expression into an equivalent postfix expression, and then evaluates the postfix expression, and then prints the result if input expression is correct otherwise prints error messages. Your program must interact with the user until the user quits.
REQUIREMENTS:
- Your simulator must work with both single digit operands and multiple digit operands.
- You must use your own stack template class or library <stack>.
- You must develop a design document to how your project works.
- Your program must produce a correct result if an input expression is correct, otherwise an error message should be given.
- You must put your functions and variables together to form a class—calculator.
CODE IN C++:
#include <bits/stdc++.h>
using namespace std;
//it is a method to find the precedence of operators
int precedence(char operand){
if(operand == '+'||operand == '-')
return 1;
if(operand == '*'||operand == '/')
return 2;
return 0;
}
// It is functin to perform arithmetic operations.
int applyOp(int x, int y, char operand){
switch(operand){
case '+': return x + y;
case '-': return x - y;
case '*': return x * y;
case '/': return x / y;
}
}
// it is function to return the value after evaluating
expression
int evaluate(string tokens){
int i;
stack <int> values;
stack <char> ops;
for(i = 0; i < tokens.length(); i++){
if(tokens[i] == ' ')
continue;
else if(tokens[i] == '('){
ops.push(tokens[i]);
}
else if(isdigit(tokens[i])){
int val =
0;
while(i <
tokens.length() &&
isdigit(tokens[i]))
{
val = (val*10) + (tokens[i]-'0');
i++;
}
values.push(val);
}
else if(tokens[i] == ')')
{
while(!ops.empty() && ops.top() != '(')
{
int val2 = values.top();
values.pop();
int val1 = values.top();
values.pop();
char op = ops.top();
ops.pop();
values.push(applyOp(val1, val2, op));
}
if(!ops.empty())
ops.pop();
}
else
{
while(!ops.empty() && precedence(ops.top())
>=
precedence(tokens[i])){
int val2 = values.top();
values.pop();
int val1 = values.top();
values.pop();
char op = ops.top();
ops.pop();
values.push(applyOp(val1, val2, op));
}
ops.push(tokens[i]);
}
}
while(!ops.empty()){
int val2 = values.top();
values.pop();
int val1 = values.top();
values.pop();
char op = ops.top();
ops.pop();
values.push(applyOp(val1, val2,
op));
}
return values.top();
}
int main() {
cout << evaluate("5 * 6 + 4 - 3")<<endl;
cout << evaluate("9 + 7 * 3") <<
endl;
cout << evaluate("65 * 2 + 12") <<
endl;
cout << evaluate("78 * ( 2 + 12 )") <<
endl;
cout << evaluate("13 * ( 2 + 12 ) /
14")<<endl;
return 0;
}
OUTPUT: