#include "lexer.h" #include using namespace std; double apply(char op, double x, double y); int main(void) { char buf[1024]; double numbers[1024]; char operators[1024]; int ntop=0; //top of the number stack int otop=0; //top of the operator stack int depth = 0; //depth of parenthen double y, x; //read a line cin.getline(buf, 1024); //lex the line LexicalElement le = nextElement(buf); do { switch(le.type) { case LPAREN: depth++; break; case RPAREN: depth--; //pop 2 operands y = numbers[--ntop]; x = numbers[--ntop]; //push the result of applying the top operator numbers[ntop++] = apply(operators[--otop], x, y); break; case OPERATOR: //push the operator onto the operator stack operators[otop++] = le.value.c; break; case NUMBER: //push onto the number stack numbers[ntop++] = le.value.num; break; } //get the next element le = nextElement(0x00); } while(le.type != ERROR && le.type != EOS); //check for errors if(le.type==ERROR) { cerr << "Syntax Error" << endl; } else if(depth != 0) { cerr << "Mismatched Parenthesis" << endl; } else { cout << "Result: " << numbers[--ntop] << endl; } return 0; } double apply(char op, double x, double y) { switch(op) { case '+': return x+y; break; case '-': return x-y; break; case '*': return x*y; break; case '/': return x/y; break; } //unreachable return 0; }