[   ^ to index...   |   <-- previous   ]

Recursion exercise solution

bool stringIsNumber(char input[]); int stringToInt(char number[]); int evaluate() { char buf[100]; cin >> buf; if (!cin) { cerr << "ERROR: bad stream while starting expression." << endl; exit(1); } else if (stringIsNumber(buf)) { // Base case of the recursion: bare number return stringToInt(buf); } else if (buf[0] == '(')) { // Read left-hand expression (which may be arbitrarily // complicated) using a recursive call int left = evaluate(); // Read operator cin >> buf; if (!cin) { cerr << "ERROR: bad stream while reading operator." << endl; } char op = buf[0]; // Read right-hand expression int right = evaluate(); // Depending on the operator, return a different // combination of the operands. switch (op) { case '+': return left + right; case '-': return left - right; default: cerr << "ERROR: invalid operator." << endl; exit(1); } } else { cerr << "ERROR: unbalanced expression." << endl; exit(1); } }

Last modified: Tue Jul 11 13:31:49 PDT 2000