postfix calculator

hello .. am still a bit new to c++ and am teaching myself
i was trying to do a postfix calculator using a strings stack
the stack alone works just fine !
this is my code for calculating the post fix formula

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374`` `````` #include "PostFixCalculator.h" double PostFixCalculator::calculate(string &expression) { double op1,op2;//first and second operands double result;//to store result of operation int index;//index of space to split formula string string temp,t;//to store part of the formula temporarly index=expression.find(" "); ostringstream sstream;//to convert from int to string while(index!=string::npos) { temp=expression.substr(0,index); if(temp=="=") break; else if(temp=="+") { op1=atof(stack.top().c_str());//convert from string to double stack.pop();//remove first element op2=atof(stack.top().c_str());//convert from string to double stack.pop();//remove first element result=op1+op2;//perform operation sstream<

now when i input a formula of any 2 numbers say like 3 100 + =
the output is 103 which is correct
but when its more than 2 numbers say like 2 2 + 2 + =
the output is 46
(4:result of the first addition, 6:result of the second) and it goes like that for every formula
i just cant figure out why its doing that!!
i appreciate any help i can get
Last edited on
Firstly, using `else if () {}` is preferable to `else{ if () {} }`
Second, what output did you want? 6 instead of 46?

Every time you are checking for an operator, you pop 2 operands from the stack, print out the result of that operation to the output stream, then push the result as a string back onto the stack. That's why you have the 4 in there.
Additionally, if you keep track of when you pop and push, you always seem to have an extra number on the stack. Hmmm.

Stack
 ```3 --> 100 --> ... --> 103 100 --> ... --> --> ... ...```
ok fixed the if statment!
but i dont understand why there is an extra number?
any suggestion what i could do to fix that?

and is it like when there is an extra input in the buffer ?
Topic archived. No new replies allowed.