The question I'm trying to answer is:
Write an object oriented C++ program to translate an infix expression to postfix.
I have done much of it but after I debug the only output is "Postfix:" and I cannot figure out why.
This is my code so far:
#include <iostream>
#include <string>
#include <stack>
#include <sstream>
using namespace std;
template<class T>
class Stack : public stack<T> {
public:
T pop() {
T tmp = top();
stack<T>::pop();
return tmp;
}
};
class inToPost {
public:
void fix();
int prec(string);
private:
Stack<string> stack;
};
void inToPost::fix() {
cout << "Enter an equation with no spaces." << endl;
cout << "For example: " << endl;
cout << "4*8+9(2-3)" << endl;
string line, str;
cin >> line;
getline(cin, line);
istringstream iss(line);
cout << "Postfix: " << endl;
while(!iss.eof()){
iss >> str;
if(str != "+" && str != "-" && str!= "/" && str != "*" && str != "(" && str != ")") {
cout << str; //While the input is none of the operators, output the variable
}
else if(str == ")") { //If the ) is encountered, pop the stack until the ( is found
while(str != "(") {
cout << stack.pop();
}
stack.pop(); //Then disregard the ( and )
}
else {
int x = prec(str); //Find the precendence
if(x > prec(stack.top())) { //If it's higher than the top element on the stack
stack.push(str); //Push the element onto the stack
}
else if(x <= prec(stack.top())) { //If it's lower
cout << stack.pop(); //Pop the top of the stack
}
}
}
while(!stack.empty()) {
cout << stack.pop();
}
}
int inToPost::prec(string str) { //Determines the precedence of the operator
if(str == "^") {
return 5;
}
else if(str == "/" || str == "*") {
return 4;
}
else if(str == "+" || "-") {
return 3;
}
else
return 0;
}
int main() {
inToPost().fix();
return 0;
}