中缀为后缀表示法

时间:2013-11-30 19:53:34

标签: c++

我正在使用中缀来修复表示法。我的程序符合,但由于某种原因它不会接受任何中缀表达式,只有后缀表达式,这与我想做的相反。这是我的计划。 我花了很长时间才能在正确的堆栈交换组上发帖。

#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时,程序崩溃。

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

2 个答案:

答案 0 :(得分:0)

在我看来,将中缀转换为后缀的更好方法是使用二叉树。您可以通过遍历顺序生成中缀或后缀。

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

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

遇到号码时,您可能希望执行以下操作:

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

答案 1 :(得分:0)

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