Consider the problem of evaluating properly parenthesized binary expressions:
( ( 1 + 2 ) + ( ( 3 - 4 ) + 5 ) )We can formulate this problem recursively:
To evaluate an expression,
- Read a token. If it is a number, return that number; otherwise, if it is a left parenthesis, continue.
- Evaluate an expression.
- Read an operator.
- Evaluate another expression.
- Read a right parenthesis.
- Return the value of steps 2, 3, and 4
Assuming there are spaces between each token, we can use cin >> to read the expression and parse it quite easily. Write the evaluate function that will read a line of input, formatted as above, and return an integer. Assume I have provided the functions stringIsNumber() and stringToInt() that will turn a string into a number, if it is a number:
For simplicity (ha), consider only + and -.
bool stringIsNumber(char input[]); int stringToInt(char number[]); int evaluate() { }