后缀表示法的插图不尊重第二组括号

Infix to Postfix notation not respecting second set of parentheses

本文关键字:二组 表示 后缀      更新时间:2023-10-16

难以获得正确的结果infix :( a b)/(c-d)后缀:ab cd-/

我继续获得后缀:ab c/d -

我确实知道问题来自于它在推动之前无法从堆栈中弹出最后一个操作员的问题"。我做错了什么?还有其他方法可以解决这个问题吗?

#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;
}

您没有设置op

const int precedence(const char x) noexcept(true) {
  switch (x) {
    case '(': case ')':
      return 1;
    case '^':
      return 2;
    case '*':
      return 3;
    case '/':
      return 4;
    case '+':
      return 5;
    case '-':
      return 6;
  }  
  return -1;
}

它返回-1,但我会让您弄清楚那部分。它没有回答这个问题。看到您可能正在阅读垃圾值后,我才停下来。

问题来自此行(!opStack.empty() && precedence(opStack.top() <=precedence(getInfix[i]))

您正在弹出您发现的最后一个操作员,而无需检查您是否在括号语句中。在将操作员添加到输出字符串之前,您需要考虑括号字符。

与您的问题无关,而是一些建议:

  • 缩进您的代码,简化可见性并相信我,节省了您(和我们)的时间。
  • 请勿push,然后为()字符pop,就像忽略它们一样。
  • 您在这条线上缺少),我想这是一个复制/粘贴问题:while (!opStack.empty() && precedence(opStack.top() <=precedence(getInfix[i]))
  • 您确实意识到自己测试了()的优先级,但是您从来没有使用该类型的字符来调用该方法?