繁体   English   中英

Postfix表示法的前缀不遵守第二组括号

[英]Infix to Postfix notation not respecting second set of parentheses

无法获得正确的Infix结果:(A + B)/(CD)后缀:AB + CD- /

我不断收到Postfix:AB + C / D-

我确实知道问题出在它不能在推送'('之前从堆栈中弹出最后一个运算符。这就是为什么我在第一个else if条件中添加if语句的原因。这也不起作用。到底是我做错了吗,还有其他方法可以解决这个问题吗?

#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]))
  • 您确实意识到您已经测试了()优先级,但是您从未真正使用该类型的字符调用该方法吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM