-3

I have a function that's taking infix expressions and converting them to prefix expressions. Here's my code:

string infixToPrefix(string expression)
{   

  stack<char> S; //holds operators
  stack<char>output; //display like in class
  string prefix = "";
  char ch;
  S.push('#');

  for (int i = expression.length(); i > 0; i--){

    ch = expression[i];

    if (isOperand(ch) == true){
      output.push(ch);

    }
    else {
      if (ch == '('){
        while (S.top() !=  ')'){
          output.push(S.top());
          S.pop();
        }
      }

      else {
        while (isp(S.top()) > icp(ch)){

          output.push(S.top());
          S.pop();

        }
        S.push(ch);

      }
    }
  }

  while (S.top() != '#'){
      output.push(S.top());
      S.pop();

    }

  while (!output.empty()){
    if (output.top() == ')'){
      output.pop();
    }
    else{
    prefix.append(1,output.top());
    output.pop();
    }
  }
  return prefix;
}

This function has worked well with the sample expressions my professor wants me to use; "3-4-5" yields "--345" and "5*(4/2)" yields "*5/42". However, this does not work with the expression "3^4^5". It keeps giving me "^^345" where its supposed to be "^3^45".

Is my algorithm incorrect? Or could this have something to do with the ICP and ISP (in the code she gave me, both have "^" = 3.)?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Riles
  • 34
  • 4
  • 2
    It is likely something to do with powers evaluating right-to-left and the others evaluating left-to-right. But I've not looked at what your code is doing to understand it; I've not used prefix operator notations before, either. – Jonathan Leffler Sep 28 '16 at 21:25
  • 1
    The code sample you gave is incomplete. No definition for `isp` or `isOperand` which definitely obscures understanding of your program. Also, do mind the indentation and general readability; remember you're asking people to help you in their lesuire time. – Tomek Sowiński Sep 28 '16 at 21:32
  • What are ISP and ICP, and where are these functions? – user207421 Sep 28 '16 at 21:56

1 Answers1

-2

SOLVED. My professor had coded that the isp of ^ = 3 and icp of ^ = 3, whereas when I changed the isp to 4 it started to work. I will take this up with my professor.

Riles
  • 34
  • 4