Hi,
I'm having trouble with a program that I have to write that is supposed to convert a prefix expression to a postfix expression using stacks. The program I wrote seems to compile fine but when I run it, it gives me a fatal error and aborts the program. I'm new to programming so I'm really lost as to why it is doing this. I would really appreciate some help.
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
#include <stdlib.h>
using namespace std;
bool isOperator(char symbol); //declaring function isOperator
int main()
{
ifstream myfile; //declaring streams
ofstream outfile;
myfile.open("Prefix.txt", ios::in); //opening streams
outfile.open("Postfix.txt", ios::out);
while (!myfile.eof()) //while not end of input file
{
stack<char> operators;
stack<char> flags;
string line;
string outputLine;
getline(myfile, line); //read the next line of file and store into ‘line’
for(int i=0; i < line.size(); i ++) //reiterate through ‘line’
{
char symbol = line [i];
if( isOperator(symbol)) //if the symbol is an operator
{
operators.push(symbol); //push operator on stack
flags.push(0); //push associated flag on stack and set to off
}
if((symbol != ' ') && !isOperator(symbol)) //then it’s a operand
{
outputLine += symbol; //append to output string
//strcat(outputLine, symbol);
//outputLine.append(symbol);
while(flags.top()) //while top flag is ON on stack
{
outputLine += operators.top() ; //append the associated op
//strcat(outputLine, operators.top());
//outputLine.append(operators.top());
operators.pop(); //remove operator from stack
flags.pop(); //remove flag from stack
}
flags.pop(); //set next flag to ON
flags.push(1);
}
}//end of for
if(!operators.empty() || (!flags.empty()) )
{
outfile << "SOMETHING WENT WRONG. Prob incorrect input" << endl;
}
else
{
outfile << "Prefix: " << line << endl;
outfile << "Postfix: " << outputLine << endl;
}
} //end of while eof
myfile.close(); //close streams
outfile.close();
}//end of main
bool isOperator(char symbol) //definition of isOperator
{
if( (symbol == '*') || (symbol == '+') || (symbol == '/') || (symbol == '-' ) )
return true;
else
return false;
}