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
#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;
elseif(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<<result;
t=sstream.str();//convert from double to string
stack.push(t);
}
elseif(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<<result;
t=sstream.str();//convert from double to string
stack.push(t);
}
elseif(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<<result;
t=sstream.str();//convert from double to string
stack.push(t);
}
elseif(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<<result;
t=sstream.str();//convert from double to string
stack.push(t);
}
else
stack.push(temp);
expression=expression.substr(index+1,expression.length());
index=expression.find(" ");
}//end of while
return atof(stack.top().c_str());//convert and return result
}
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
thank you in advance ^_^
Firstly, using elseif () {} 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.