// inFix to post fix converter
//This does it correctly but, the User must type in the statement but they are given what to type.
#include<iostream>
#include<stdio.h>
#include<conio.h>
#include<vector>
#include<string>
#include <stdlib.h>
#include <stdio.h>
#include<stdlib.h>
#include<fstream>
const int size =50;
char postfix[size],stack[size];
int top=-1;
int precedence(char ch); // get the precedence of the operator
char pop(); // pop an element from the stack
char topelement(); // returns the top element of the stack
void push(char ch); // pushes an element into the stack
using namespace std;
int main()
{
//string getdata;
//int cont=0;
//fstream data;
// data.open("C:\\InFix.txt",ios::in);
//while(!data.eof()){
//data.getline(getdata,sizeof(data));
// cout<<getdata<<endl;
//}
// system("pause");
ifstream inFile("C:\\InFix.txt");
ifstream ftext;
string word;
// cout << getdata; //THis is EMPTY!
cout << "Please type The following statement";
cout << "\n";
cout << "\n";
cout << "THis will convert what is in InFix.txt to Post Fix";
cout << "\n";
char ele,elem,st[2];
int prep,pre,popped,j=0,chk=0;
strcpy(postfix," ");
char dirt[size] = "lol";
cout << dirt;
//Gets the inFIx typed but this is acutally getting written to the textfile not what you wrote.
//gets(infix);
char infix[size] = "X = A + B"; // this is where the contents of the text file needs to go.
for(int i=0;infix[i]!=0;i++)
{
if(infix[i]!='('&&infix[i]!=')'&&infix[i]!='^'&&infix[i]!='*'&&infix[i]!='/'&&infix[i]!='+'&&infix[i]!='-')
postfix[j++]=infix[i];
else if(infix[i]=='(')
{
elem=infix[i];
push(elem);
}
else if(infix[i]==')')
{
while((popped=pop()) != '(')
postfix[j++]=popped;
}
else
{
elem=infix[i];
//stores precedence of operator from infix
pre=precedence(elem);
ele=topelement();
//stores precedence of operator at top stack
prep=precedence(ele);
if(pre > prep)
push(elem);
else
{
while(prep >= pre)
{
if(ele=='#')
break;
popped=pop();
ele=topelement();
postfix[j++]=popped;
prep=precedence(ele);
}
push(elem);
}
}
}
while((popped=pop())!='#')
postfix[j++]=popped;
postfix[j]='\0';
cout<<"\n post fix Version :"<<postfix<<endl;
//was able to write to a file but, only overwrote the exisiting file
inFile.close();
system("pause");
return 0;
}
int precedence(char ch)
{
switch(ch)
{
case '^' : return 5;
case '/' : return 4;
case '*' : return 4;
case '+' : return 3;
case '-' : return 3;
case '=' : return 2;
default : return 0;
}
}
char pop()
//pop the element from the stack
{
char ret;
if(top!=-1)
{ ret =stack[top];
top--;
return ret;
}
else
return '#';
}
char topelement()
// return top element from the stack without popping
{
char ch;
if(top!=-1)
ch=stack[top];
else
ch='#';
return ch;
}
void push(char ch)
// push an element in the stack
{
if(top!=size-1)
{
top++;
stack[top]= ch;
}
}
This post has been edited by mister1337: 23 September 2009 - 08:27 AM

New Topic/Question
Reply




MultiQuote








|