Infix to Postfix sending out an operator incorrectly

48 views Asked by At

I am doing a project where i take in an infix expression and change it to a postfix expression using a string array. I have passed several of the test cases and am having a hard time understanding what is occurring in the final test case. My infix expression is 2 + 3 * 4 - 10 / 5 % 3. This should turn out to be 2 3 4 * + 10 5 / 3 % -. However, when i run the code i am getting 2 3 4 * + 10 5 / - 3 %.

I have posted the relevant pieces of code below.

#include <iostream>
#include <string>
#include <stack>

//sets precedent for operators
using namespace std;

int precedent(string opera){
  if(opera == "*" || opera == "/")
    return 2;
  else if(opera == "-" || opera == "+")
    return 1;
  else
    return -1;
}

int infixToPostfix(string infix[], int length, string postfix[])
{
    stack<string> op;      //initiates stack for operator symbols temp holding
    int count = 0;             //to keep track of values


    //loops through array.
    for (int j = 0; j < length; j++){
      string d = infix[j];          //temp holding place for values
      //checks for numbers for next 3 statements.
      //if statement is found it adds to postfix and counts
      if(d >= "0" && d <= "9"){
        postfix[count] = d;
        count++;
      }

      //if next string is "(" it pushes it into the stack
      else if(d == "("){
        op.push("(");
      }
      //if next string is ")" it pops all values in the stack to
      //the postfix array until "(" is reached
      else if(d == ")"){
        while(op.top() != "("){
          postfix[count] = op.top();
          op.pop();
          count++;
        }
        op.pop();
      }
      //takes in operators and organizes them correctly for insertion into postfix
      ///*
      else{
        while (!op.empty() && precedent(d) <=  precedent(op.top())){
          //cout<<"check for while";
          postfix[count] = op.top();
          op.pop();
          count++;
        }
        op.push(d);
      }
     //*/
    }
    while (!op.empty()){
      postfix[count] = op.top();
      op.pop();
      count++;
    }

    length = count;
    return length;
}

I have tried to test to see if the subtraction operator is maybe getting added prematurely because the while loop isnt exiting correctly but came up empty handed. honestly lost on what else it could be.

0

There are 0 answers