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
now when i enter a formula of any 2 numbers say like 1 2 + =
the output is 3 which is correct (goes for anhy other formula)
but when its more than 2 numbers the result is wrong
i just cant figure out why its doing that!!
any help is really appreciated
thank you in advace
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;
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<<result;
t=sstream.str();//convert from double to string
stack.push(t);
}
else
{
if(temp=="-")
{
// string x=stack.top();
op1=atof(stack.top().c_str());//convert from string to double
stack.pop();//remove first element
// x=stack.top();
op2=atof(stack.top().c_str());//convert from string to double
stack.pop();//remove first element
result=op1-op2;//perform operation
//cout<<result<<endl<<"r"<<endl;
sstream<<result;
t=sstream.str();//convert from double to string
stack.push(t);
}
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<<result;
t=sstream.str();//convert from double to string
stack.push(t);
}
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<<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(" ");
}
return atof(stack.top().c_str());//convert and return result
}
now when i enter a formula of any 2 numbers say like 1 2 + =
the output is 3 which is correct (goes for anhy other formula)
but when its more than 2 numbers the result is wrong
i just cant figure out why its doing that!!
any help is really appreciated
thank you in advace