Reputation: 255
#include <iostream>
#include <stack>
#include <string>
#include <sstream>
using namespace std;
stack<char> aStack;
stringstream result;
stack<char> operand1;
stack<char> operand2;
stringstream &postfixExp(string ch){
for(int i =0; i< ch.length(); i++)
{
if(ch[i]== '1' || ch[i]== '2' || ch[i]== '3' || ch[i]== '4' || ch[i]== '5' || ch[i]== '6' || ch[i]== '7' || ch[i]== '8' || ch[i]== '9' || ch[i]== '0' )
{
aStack.push(ch[i]);
}
else if( ch[i]== '+')
{
operand2.push(aStack.top());
aStack.pop();
operand1.push(aStack.top());
aStack.pop();
result << ( operand1.top() + operand1.top());
}
}
return result;
}
int main()
{
string postfix = " 2+3";
stringstream* answer = &postfixExp(postfix);
cout << "Result = " << answer->str() << endl;;
return 0;
}
Hi everyone, does anyone know what is wrong with my code ? I do not see any error message from the compiler. However it crashes when I run it.
I'm having a difficult time to display the result which I got from my function. I initially wanted to use a stack function, but I couldn't think of how to pass the value to the main function and display it.
Then I'm thinking to use stringstream function instead. Unfortunately, I still don't know how to display the corresponding result
I wonder if anyone could tell me which part is wrong in my code, or if there is a better way to display the result from the function other than using stringstream or stack
Thanks a lot!
Upvotes: 0
Views: 1320
Reputation: 42083
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();
}
Upvotes: 1
Reputation: 880
Test input for a postfix arithmetic operation should be in the form of "23+", not "2+3".
Some checks should probably be added to ensure you're not popping from an empty stack, as others have mentioned.
Upvotes: 0