/****************************************************************************** Dr. K Zemoudeh, Date: 1/12/98, File: exprEval.cpp Modified RJBotting Sun Nov 7 08:12:17 PST 2004 This programs evaluates simple expressions that consist of whole numbers, -, +, *, /, ^ (exponentiation), ), and ( operators. Each expression is input with values and operators separated by white space and must be terminated by an equal sign. It performs little error checking, and assumes all operators are left to right associative. ^ has the highest precedence, * and / are at the next lower level, and + and - are at the lowest precedence. This program illustrates the use of Stack data structure. ******************************************************************************/ #include #include // for atoi(), exit(), and EXIT_FAILURE #include #include // for pow() #include #include "stack.h" using namespace std; // Functions used in main program void evaluate(Stack& operand, Stack& oprator); int convert(string); bool isOperator(string); int intValue(string); main() { try{ Stack operand, oprator; // 'operator' is a special C++ word. int op; // integer equivalent of the operator returned from convert() string token; cout << "input an expression ending with =. Separate integers and operators.\n"; cin >> token; while (token != "=") { if (isOperator(token)) if (token == ")") { while (oprator.top() != 6) // 6 == "(" evaluate(operand, oprator); oprator.pop(); // pop "(" } else { op = convert(token); while (!oprator.empty() && oprator.top() != 6 && op <= oprator.top()) evaluate(operand, oprator); oprator.push(op); } else // token is a number operand.push(intValue(token)); cin >> token; } while (!oprator.empty()) evaluate(operand, oprator); cout << operand.top() << endl; operand.pop(); } catch(exception &e) { cerr<< "Exception thrown: "<< typeid(e).name()<< " " << e.what()< } // intValue