As it was pointed out already, error is caused by calling aStack.pop();
while the aStack
container is empty. This probably yields undefined behavior that (in this case) you are able to observe as a crash of your application.
Explanation is simple, you process string "2+3"
character by character:
for each character:
if it is digit:
push it to stack
if it is '+':
pop 2 elements
... so what do you think will happen in "2+3"
string once the '+'
sign is reached?
Also consider redesigning this:
stringstream result;
stringstream& postfixExp(string ch) {
...
return result;
}
... you're returning a reference to global variable, which means you either shouldn't return anything or the variable shouldn't be global. Yet even better, consider passing only std::string
objects instead (use stringstream
locally within the function):
std::string postfixExp(const std::string& expression) {
std::ostringstream resultStream;
...
return result.str();
}