I have adopted the algorithm to start the main loop at the end of the string and work backwards, as well as reverse the string at the end (like they stated) to accommodate going to prefix instead of postfix. This works fine for expressions not containing parenthesis, but on line 44 I get a dereference error (trying to access the top value of the stack when there is no top value). Can't figure out how to modify the case for the close parenthesis:
void infixToPrefix(std::string &expr)
{
//Use temp as a working string.
std::string temp = expr;
//Clear the input/output string and use it as the output queue.
expr.clear();
std::stack <char> opStack;
//Because of prefix, start at the end of the string and work down.
for (int i = temp.length() - 1; i >= 0; --i)
{
constchar cur = temp[i]; //avoid tonnage of dereferences.
switch (cur)
{
case'*':
case'/':
case'+':
case'-':
//All this works fine.
while (!opStack.empty() && (precedence(opStack.top()) <= precedence(cur)))
{
expr.push_back(opStack.top());
opStack.pop();
}
opStack.push(cur);
break;
case'(': //We are on an opening parenthesis.
//Push it on to the opStack as well;
opStack.push(cur);
break;
case')': //We are on a closing parenthesis.
//Start removing operators from the opStack until the open
//parenthesis is found.
while (opStack.top() != '(')
{
//Push the operator from the top of the stack into the expression.
expr.push_back(opStack.top());
//Pop that operator from the stack.
opStack.pop();
} //end while
opStack.pop();
break;
default:
expr.push_back(cur);
break;
}
}
while (!opStack.empty())
{
expr.push_back(opStack.top());
opStack.pop();
}
//reverse the string
expr = std::string(expr.rbegin(), expr.rend());
}
int main(int argc, char *argv[])
{
std::string expr = "(a+b)*c";
std::cout << expr << std::endl;
infixToPrefix(expr);
std::cout << expr;
return 0;
}