evualation of postfix expression
Mar 18, 2013 at 5:28pm UTC
hello programmers i need help to solve this i write a code that solve the Postfix Expression but there are two problems...if there is 22 in my expression the code treated is as 2,2 and produce a result similarly if there is a number 2.2 in expression the code break it in this form 2,.,2... u can see this and can be easily understand what i want say...
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 37 38 39
#include<iostream>
#include<conio.h>
#include"stack1.cpp"
#include<string>
using namespace std;
void main()
{
stack s;
float p1,p2,res=0;
char string[20];
cout<<"Enter the postfix expression.." ;
cin.getline(string,20);
for (int i=0;string[i]!='\0' ;i++)
{
if (string[i]>='0' && string[i]<='9' )
s.push((float )string[i]-'0' );
else
{
p2=s.pop();
p1=s.pop();
if (string[i]=='+' )
res=p1+p2;
else if (string[i]=='-' )
res=p1-p2;
else if (string[i]=='*' )
res=p1*p2;
else if (string[i]=='/' )
res=p1/p2;
else if (string[i]=='$' )
{ res=1;
for (int n=1;n<=p2;n++)
res=res*p1;
}
s.push(res);
}
}
cout<<"\nResult is:" <<s.pop();
getch();
}
Mar 19, 2013 at 3:48pm UTC
i there any help????
Mar 19, 2013 at 3:59pm UTC
You can use a flag indicating if the last character was a number or symbol:
1 2 3 4 5 6 7 8 9 10 11 12
if (string[i]>='0' && string[i]<='9' ){
if (fNumber)
s.push(s.pop()*10 + (float )string[i]-'0' );
else {
fNumber = true ;
s.push((float )string[i]-'0' );
}
}
else
{
fNumber = false ;
Topic archived. No new replies allowed.