trying to write a calculator
Feb 18, 2014 at 11:28pm UTC
I'm trying to write a calculator program that places int in one stack and char in another, checks the precedence of the char and then if the precedence is high than the char on the stack, performs the operation.
This is what I have so far, but it doesn't seem right to me.
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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
#include <cstdlib>
#include <iostream>
#include "Calculator.h"
void Calculator::processOperator ()
{
int temp;
while (!operators.isEmpty())
{
int x = operands.peek();
operands.pop();
int y = operands.peek();
operands.pop();
char op = operators.peek();
operators.pop();
switch (op)
{
case '+' : temp = x + y;
break ;
case '-' : temp = x - y;
break ;
case '*' : temp = x * y;
break ;
case '/' : temp = x / y;
break ;
default : cout << "Invalid operator, press any key to terminate." ;
}//end switch
operands.push(temp);
}//end while
}//end processOperator()
bool Calculator::higherPrecedence(char op)
{
if (op >= operators.peek())
{
return true ;
}// end if
else
{
return false ;
}//end else
}//end higherPrecedence()
int Calculator::calculate ()
{
cout << "Please enter an expression: " << endl;
cin >> expression;
for (int i; i < expression.length(); i++)
{
char op = operands.peek();
higherPrecedence(op);
if (higherPrecedence(op) == false ) //if a
{
if (!isOperator(expression[i]))// if b
{
int tempOp = getOperand(i);
operands.push(tempOp);
}//end if b
else if (isOperator(expression[i]))
{
operators.push(expression[i]);
}//end for
}//end if a
else
{
processOperator();
}
}//end for
}//end calculate()
Topic archived. No new replies allowed.