Postfix Evaluation
#define max_items 50
typedef int itemtype;
#include<iostream>
#include<string>
#include<math.h>
#include<fstream>
using namespace std;
class posteval
{
private:
string input;
itemtype result;
int top;
itemtype *items;
int cheak;
int counter;
public:
posteval();
void getexp();
void display();
bool isfull();
bool isempty();
void push(itemtype x);
itemtype pop();
void eval();
void cheakexp();
};
posteval::posteval()
{
top=-1;
items=new itemtype[max_items];
input=" ";
result=0;
cheak=0;
counter=0;
}
void posteval::getexp()
{
ifstream myfile("test.txt");
myfile>>input;
}
void posteval::display()
{
cout<<"\nThe resultant of the given postfix expression is : "<<result<<endl;
}
bool posteval::isfull()
{
if (top==max_items)
{
return 1;
}
else
{
return 0;
}
}
bool posteval::isempty()
{
if (top==-1)
{
return 1;
}
else
{
return 0;
}
}
void posteval::push(itemtype x)
{
if(isfull())
{
cout<<"\nStack Overflow";
exit(1);
}
else
{
top++;
items[top]=x;
}
}
itemtype posteval::pop()
{
itemtype z;
if(isempty())
{
cout<<"\nStack Underflow";
exit(1);
}
else
{
z=items[top];
top--;
return z;
}
}
void posteval::eval()
{
char exp;
itemtype operand1;
itemtype operand2;
exp=input[cheak];
while(cheak<input.length())
{
if(exp=='0'||exp=='1'||exp=='2'||exp=='3'||exp=='4'||exp=='5'||exp=='6'||exp=='7'||exp=='8'||exp=='9')
{
int x;
x=exp-48;
push(x);
}
else
{
operand2=pop();
operand1=pop();
if(exp=='+')
{
result=operand1+operand2;
}
else if(exp=='-')
{
result=operand1-operand2;
}
else if(exp=='*')
{
result=operand1*operand2;
}
else if(exp=='/')
{
result=operand1/operand2;
}
else if(exp=='$')
{
result=pow(operand1,operand2);
}
push(result);
}
cheak++;
exp=input[cheak];
}
if(!isempty())
{
result=pop();
}
}
void posteval::cheakexp()
{
for (int i=0;i<input.length();i++)
{
if(input[i]=='0'||input[i]=='1'||input[i]=='2'||input[i]=='3'||input[i]=='4'||input[i]=='5'||input[i]=='6'||input[i]=='7'||input[i]=='8'||input[i]=='9')
{
counter++;
}
else
{
counter-=1;
}
}
if(counter==1)
{
posteval::eval();
posteval::display();
}
else
{
cout<<"\nExpression is invalid\n";
}
}
void main()
{
posteval ob;
ob.getexp();
ob.cheakexp();
}
0 comments:
Post a Comment