繁体   English   中英

后缀表示法的前缀

[英]infix to postfix notation

我正在做infix发布修订符号。 我的程序符合要求,尽管出于某种原因,它不会包含任何中缀表达式,而仅包含后缀表达式,这与我想做的相反。 这是我的程序。 我花了很长时间才张贴在正确的堆栈交换组上。

#include <iostream>
#include <string>
#include <sstream>
#include <stack>
using namespace std;

string infixexpr (istream&  in)
{
//Holds value in computation
stack<string> postfixstack;
//used to to read in characters from the expression
char ch;
// used to read in numbers from expression
int num;
// Used to remove infix expressions from stack
string lexpr, rexpr;
ch = in.peek();
while ( ch != EOF)
{
    //If we have a whitespace character skip it and continue with
    // the end of the loop.
    if(isspace(ch))
    {
        ch = in.get();
        ch =in.peek();
        continue;
    }

//nonspace character is next to input stream
// if the next character is a number read it and convert it
// to string then put the string onto the postfix stack

if (isdigit (ch))
{
    in >> num;
    // use to convert string
    ostringstream numberstr;
    // convert to number using sstream
    numberstr << num;
    // Push the representing string onto stack0
    postfixstack.push(numberstr.str());
    ch = in.peek();
    continue;
}

// if operator pop the two postfix expressions
// stored on the stack, put the operator after
    // the two expressions
rexpr = postfixstack.top();
postfixstack.pop();
lexpr = postfixstack.top();
postfixstack.pop();


if (ch == '+' || ch == '-' || + ch == '*' || ch == '/' || ch == '%')
    postfixstack.push(rexpr + " " + lexpr + " " + ch);
else
{
    cout << "Error in input expression" << endl;
    exit(1);
}
ch = in.get();
ch = in.peek();
}
return postfixstack.top();
}



int main1()
{
string input;
cout <<  "Enter a infix expression to convert to postfix,"
     << " \nor a blank line to quit the program:";
getline(cin,input);

while (input.size() != 0 )
{
    //convert string to a string stream
    istringstream inputExpr(input);
    cout << "the infix equavilent is: "
         << infixexpr(inputExpr) << endl;
        cout << "Enter a infix Expression to evaluate: ";
        getline(cin,input);
}

return 0;
   }

这是我所知道的:

如果您在当前状态下运行该程序,它将采用后缀表示法:1 2 +并将其隐藏为后缀。 这不是我想要的。

问题发生在lexpr = postfixstack.top() ,其中top是指向堆栈中第一个节点的指针,我认为它没有指向任何东西。 我还认为,当我尝试弹出某些内容时,没有任何内容可以弹出,因此会出错。 我不确定如何解决此问题。

当用户放置一个中缀概念:1 + 2时,程序崩溃。

*更正我正在使用堆栈头及其功能。

我认为,将中缀转换为后缀的更好方法是使用二叉树。 您可以根据遍历顺序生成中缀或后缀。

您没有为lexprrexpr分配任何值,而是在遇到运算符时使用它们。

在编码之前,您是否曾用笔和纸尝试过算法?

遇到数字时,您可能需要执行以下操作:

if number is first value in expression, push value.
else
{
  operator = stack.pop();
  stack.push(number);
  stack.push(operator);
}

您的代码清单不包含lexpr = postfix stack.top()如您的问题所建议。 实际上,它不会在任何地方为lexpr或rexpr分配任何内容。 我希望会有一些行将值从堆栈弹出到lexpr和rexpr中。

暂无
暂无

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

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