01: #include <iostream> 02: #include <cctype> 04: using namespace std; 06: int term_value(); 07: int factor_value(); 09: /** 10: Evaluates the next expression found in cin 11: @return the value of the expression. 12: */ 13: int expression_value() 14: { int result = term_value(); 16: bool more = true; 17: while (more) 18: { char op = cin.peek(); 20: if (op == '+' || op == '-') 21: { cin.get(); 23: int value = term_value(); 24: if (op == '+') result = result + value; 25: else result = result - value; 26: } 27: else more = false; 28: } 29: return result; 30: } 32: /** 33: Evaluates the next term found in cin 34: @return the value of the term. 35: */ 36: int term_value() 37: { int result = factor_value(); 39: bool more = true; 40: while (more) 41: { char op = cin.peek(); 43: if (op == '*' || op == '/') 44: { cin.get(); 46: int value = factor_value(); 47: if (op == '*') result = result * value; 48: else result = result / value; 49: } 50: else more = false; 51: } 52: return result; 53: } 55: /** 56: Evaluates the next factor found in cin 57: @return the value of the factor. 58: */ 59: int factor_value() 60: { int result = 0; 62: char c = cin.peek(); 63: if (c == '(') 64: { cin.get(); 66: result = expression_value(); 67: cin.get(); // read ")" 68: } 69: else // assemble number value from digits 70: { while (isdigit(c)) 72: { result = 10 * result + c - '0'; 74: cin.get(); 75: c = cin.peek(); 76: }
77: } 78: return result; 79: } 80: 81: int main() 82: { cout << "Enter an expression: "; 84: cout << expression_value() << endl; 85: return 0; 86: }