jeudi 20 décembre 2018

Infix to Postfix notation not respecting second set of parentheses

Having trouble getting the correct outcome of Infix: (A+B)/(C-D) Postfix: AB+CD-/

I keep getting Postfix: AB+C/D-

I do know that the issue is coming from it not being able to pop the last operators from the stack before pushing '(' This is why I added the if statement in the first else if condition. That also doesn't work. What is it exactly that I am doing wrong? Is there another way into tackling this problem?

#include <iostream>
#include <stack>
#include <sstream>
#include <string>
using namespace std;

int precedence(char x) {
int op;
if (x == '(' || x==')')
    op = 1;
else if (x == '^')
    op = 2;
else  if (x == '*')
    op = 3;
else  if ( x == '/')
    op = 4;
else  if (x == '+')
    op = 5;
else  if (x == '-')
    op = 6;
return op;
}

int main() {
string getInfix;
cout << "Infix: ";
getline(cin, getInfix);
stack<char> opStack;
stringstream showInfix;


for (unsigned i = 0; i < getInfix.length(); i++) {

if (getInfix[i] == '+' || getInfix[i] == '-' || getInfix[i] == '*' ||
getInfix[i] == '/'  || getInfix[i] == '^'  ) {

while (!opStack.empty() && precedence(opStack.top() 
<=precedence(getInfix[i])) 
  {
   showInfix << opStack.top();
   opStack.pop();
  }
 opStack.push(getInfix[i]);
}

  else if (getInfix[i] == '(') {
    opStack.push(getInfix[i]);
    opStack.pop();

    if (getInfix[i]=='(' && !opStack.empty()){
        opStack.push(getInfix[i]);
        opStack.pop();
     }
    }

    else if (getInfix [i]==')'){                   
      showInfix << opStack.top();
      opStack.pop();
    }

    else {
     showInfix << getInfix[i];
    }
  }


while (!opStack.empty()) {
    showInfix << opStack.top();
    opStack.pop();
}

cout << "Postfix: "<<""<<showInfix.str() << endl;

cin.ignore ( numeric_limits< streamsize >:: max(),'\n');
return 0;
}

Aucun commentaire:

Enregistrer un commentaire