Write in C++:
Write a program to convert a text-file containing expressions (one per line) into post-fix expressions outputted to a file of your choice using a stack with one space between operators and variables ( one letter variables) and/or constants (one digit constants).
//------------ main.cpp --------
#include<bits/stdc++.h>
#include<fstream>
using namespace std;
//function that returns the precedence as an integer.
int getPrecendence(char c)
{
switch(c)
{
case '+':
return 1;
break;
case '-':
return 1;
break;
case '*':
return 2;
break;
case '/':
return 2;
break;
case '^':
return 3;
break;
default:
return -1;
break;
}
}
//function that returns the type of given char
//like variable or contant or operator or ( or ) or something
else.
int getType(char ch)
{
if((ch >='a' && ch <='z') || (ch >='A' &&
ch <='Z'))
{
return 0;
}
else if(ch >='0' && ch <='9')
{
return 0;
}
else if(ch == '(')
{
return 1;
}
else if(ch == ')')
{
return 2;
}
if(getPrecendence(ch) != -1)
{
return 3;
}
else
{
return -1;
}
}
//function that takes a string in infix notation
//and returns the postfix expression for it.
bool convertInfixToPost(string infix,string &res)
{
string postfix = "";
stack<char> st;
int len = infix.length();
st.push('$');
res ="";
int charType;
char ch;
for(int i =0;i<len;i++)
{
charType = getType(infix[i]);
if(charType == 0)
{
res += infix[i];
}
else if(charType == 1)
{
st.push('(');
}
else if(charType == 2)
{
while(st.top() != '$' && st.top() !='(')
{
ch = st.top();
st.pop();
res += ch;
}
if(st.top() == '(')
{
ch = st.top();
st.pop();
}
}
else if(charType == 3)
{
while(st.top() != '$' && getPrecendence(infix[i]) <=
getPrecendence(st.top()))
{
ch = st.top();
st.pop();
res += ch;
}
st.push(infix[i]);
}
else
{
cout<<"\nInvalid character in expression:
"<<infix[i]<<endl;
cout<<"Invalid Expression. Excluding this expression:
"<<infix<<endl;
return false;
}
}
while(st.top() != '$')
{
ch = st.top();
st.pop();
res += ch;
}
return true;
}
//function that loads the input file and write the valid
expressions
// to output file.
void loadAndWrite(string inpFile,string outFile)
{
ifstream inp(inpFile.c_str());
ofstream out(outFile.c_str());
if(inp.fail())
{
cout<<"\nUnable to open file:
"<<inpFile<<endl;
return;
}
string line;
string post="";
cout<<"\n";
while(getline(inp,line))
{
if(convertInfixToPost(line,post))
{
cout<<"Equivalent Postfix expression for expression:
"<<line<<" is: "<<post<<endl;
out << post<<"\n";
}
}
inp.close();
out.close();
}
int main()
{
//load expressions from inp.txt and write to out.txt.
loadAndWrite("inp.txt","out.txt");
return 0;
}
//----------- SAMPLE OUTPUT ---------
/*
//------- INP.TXT -----
a+b+c
a/b^c
a-b+c*d
1+2^3/6
//------------- OUT.TXT ------
ab+c+
abc^/
ab-cd*+
123^6/+
*/
//PLEASE LIKE THE ANSWER AND COMMENT IF YOU HAVE ANY DOUBTS.
Get Answers For Free
Most questions answered within 1 hours.