    01: #include <iostream>
    02: #include <cctype>
    03:
    04: using namespace std;
    05:
    06: int term_value();
    07: int factor_value();
    08:
    09: /**
    10:    Evaluates the next expression found in cin
    11:    @return the value of the expression.
    12: */
    13: int expression_value()
    14: {
    15:    int result = term_value();
    16:    bool more = true;
    17:    while (more)
    18:    {
    19:       char op = cin.peek();
    20:       if (op == '+' || op == '-')
    21:       {
    22:          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: }
    31:
    32: /**
    33:    Evaluates the next term found in cin
    34:    @return the value of the term.
    35: */
    36: int term_value()
    37: {
    38:    int result = factor_value();
    39:    bool more = true;
    40:    while (more)
    41:    {
    42:       char op = cin.peek();
    43:       if (op == '*' || op == '/')
    44:       {
    45:          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: }
    54:
    55: /**
    56:    Evaluates the next factor found in cin
    57:    @return the value of the factor.
    58: */
    59: int factor_value()
    60: {
    61:    int result = 0;
    62:    char c = cin.peek();
    63:    if (c == '(')
    64:    {
    65:       cin.get();
    66:       result = expression_value();
    67:       cin.get(); // read ")"
    68:    }
    69:    else // assemble number value from digits
    70:    {
    71:       while (isdigit(c))
    72:       {
    73:          result = 10 * result + c - '0';
    74:          cin.get();
    75:          c = cin.peek();
    76:       }
    77:    }
    78:    return result;
    79: }
    80:
    81: int main()
    82: {
    83:    cout << "Enter an expression: ";
    84:    cout << expression_value() << endl;
    85:    return 0;
    86: }