Question: Creating a program that converts infix to postfix when reading from an input file (until it hits a '.')and outputting to a file. It is
Creating a program that converts infix to postfix when reading from an input file (until it hits a '.')and outputting to a file. It is reading in my input well except that it keeps throwing a ) after each input read in. Also it is not outputting my postfix expressions correctly, it seems to be adding them together and not even converting them correctly.
My input file:
A+B -C; A + C ;
x*(y+z)-(w+t); A+B*(C+D)-E/F+G+H;
A*B.
Garbage here.
My output.txt results
Infix: A+B-C;) Postfix: (A+B-C;) Infix: A+C;) Postfix: (A+B-C;)(A+C;) Infix: x*(y+z)-(w+t);) Postfix: (A+B-C;)(A+C;)(x(*y+z)(-w+t);) Infix: A+B*(C+D)-E/F+G+H;) Postfix: (A+B-C;)(A+C;)(x(*y+z)(-w+t);)(A+B(*C+D)-E/F+G+H;) Infix: A*B.) Postfix: (A+B-C;)(A+C;)(x(*y+z)(-w+t);)(A+B(*C+D)-E/F+G+H;)(A*B.)
EXPRESSION.H:
#ifndef EXPRESSION__H #define EXPRESSION__H #include
class expression { public: bool last; expression(); friend std::istream& operator>>(std::istream&, expression&); friend std::ostream& operator<<(std::ostream&, expression&); void convertToPostFix();
private: std::string ifix, pfix; //convert here move bool const precedence(char, char); };
#endif
EXPRESSION.CPP:
#include
using namespace std;
expression::expression() {
stack stack; stack.push('('); ifix.push_back(')');
for (size_t i = 0; i < ifix.size(); ++i) {
if (isdigit(ifix[i]) || isspace(ifix[i])) { pfix.push_back(ifix[i]); }
else if (ifix[i] == '(') { stack.push(ifix[i]); }
else if ((ifix[i])) { char operator1 = ifix[i]; if ((stack.top())) { while (!stack.empty() && precedence(operator1, stack.top())) { pfix.push_back(stack.top()); stack.pop(); } } stack.push(operator1); } else if (ifix[i] == ')') { while (stack.top() != '(') { pfix.push_back(stack.top()); stack.pop(); } stack.pop(); } }
while (!stack.empty()) { pfix.push_back(stack.top()); stack.pop(); } }
std::istream& operator>>(std::istream& in, expression& exp){ char sym; exp.ifix = ""; do { in >> sym; exp.ifix += sym; } while (sym != '.' && sym != ';'); if (sym == '.') exp.last = true; exp.convertToPostFix(); return in; }
std::ostream& operator<<(std::ostream& out, expression& exp) { out << "Infix: " << exp.ifix << std::endl; out << "Postfix: " << exp.pfix << std::endl; return out; }
in2post.cpp: (where im reading in/out)
#include "expression.h" //#include "stack.h" //#include "queue.h" #include
using namespace std;
int main(){ ifstream fin; ofstream fout; expression exp; queue q; fin.open("input.txt"); fout.open("output.txt");
while (!exp.last) {
fin >> exp; q.push(exp); } fin.close(); while (!q.empty()) { exp = q.front(); fout << exp; q.pop(); } fout.close(); return 0; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
