I'm doing a program that work out "Reverse Polish Notation" algorithm. Part of my code is this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
while( !queue.empty() )
{
token = queue.front();
queue.pop();
if( isdigit(token[0]) )
stack.push(token);
else
{
opr1.clear();
opr2.clear();
opr1 << stack.top();
stack.pop();
opr2 << stack.top();
stack.pop();
opr1 >> x;
opr2 >> y;
result = new stringstream;
switch( token[0] )
{
case '+': *result << y + x;
break;
case '-': *result << y - x;
break;
case '*': *result << y * x;
break;
case '/': *result << y / x;
break;
}
stack.push( result->str() );
delete result;
}
}
|
It works correctly. However, if I were to change the
result variable from type
stringstream* to
stringstream, it wouldn't work correctly anymore. Assuming in the first while loop, operation between
y and
x produces "2" (push "2" to stack thanks to result.str() ) and in the second time the loop executes, the operation produces "-3", then the thing being pushed to stack the second time is "2-3" and not just "-3".
I tried .flush() and .clear() but both didn't work out for me, so I had to resort to new-ing and deleting a pointer everytime.
Why do
opr1 and
opr2 (of type stringstream) can get data from stack and extract them to
x and
y correctly, but not the
result?
My previous attempt (which is wrong and didn't work) is something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
while( !queue.empty() )
{
token = queue.front();
queue.pop();
if( isdigit(token[0]) )
stack.push(token);
else
{
opr1.clear();
opr2.clear();
result.clear();
result.flush();
opr1 << stack.top();
stack.pop();
opr2 << stack.top();
stack.pop();
opr1 >> x;
opr2 >> y;
switch( token[0] )
{
case '+': result << y + x;
break;
case '-': result << y - x;
break;
case '*': result << y * x;
break;
case '/': result << y / x;
break;
}
stack.push( result.str() );
delete result;
}
}
|
Any input as to why the problem occurred as well as how to make this part looks less like a mess, is really appreciated.
Thanks in advance.