Originally Posted by
grumpy
The error lies in your expectations. C and C++ I/O do not evaluate expressions like that at all.
The sequence that will occur when you enter the expression (5-9) is that cin will first contain an opening bracket. That character is examined, deemed not to be a digit of an integral value, and left in the stream. So the streaming operator (invoked by cin >> exp; ) returns immediately, without changing the value of the variable exp.
The value 2 being output is whatever the value exp happens to hold before you attempt to read input from cin. exp is an uninitialised variable (you have not initialised it with any value) and it stays uninitialised. Accessing the value of an uninitialised variable (and printing a variable means its value must be accessed) formally yields undefined behaviour, according to the C++ standard. That means anything is allowed to happen: a program crash, printing 2, printing 42, or anything else. It just so happens your program retrieves the value 2 and prints that out.
If you want the user to be able to enter expressions, you have to write code that explicitly interprets the user input, possibly one character at a time, in order to interpret the user input as an expression. I'll leave working out how to do that as an exercise.