我的数学表达式转换器无法正确打印

时间:2013-04-19 14:05:48

标签: c++ parsing

所以,我正在编写一个程序,它接受输入(数学表达式)并将其转换为后缀表示法,然后将其打印出来给用户。当我用简单的数学表达式(即5 + 1 - 3 * 2)执行这个程序时,它运行得很好。问题是当我包括括号时。它打印最后一行的所有数学运算符而不是它们的适当位置。我需要数学运算符在他们适当的位置。 (即5 1 + 3 - 2 *)。有什么建议吗?

此声明5 - ( 2 * 3 ) + 5的实际输出为5 2 3 5 * - +我需要它看起来像5 2 3 * - 5 +

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

int priority(string item) //prioritizing the operators
{
  if(item == "(" || item == ")")
  {
    return 0;
  }
  else if(item == "+" || item == "-")
  {
    return 1;
  }
  else if(item == "/" || item == "*")
  {
    return 2;
  }
}
void welcome()
{
 cout << "blah blah!" << endl;
 }
int main()
{   

welcome(); // welcome text

stack <string> myStack; 
char line[256]; 
cin.getline( line, 256); 
string exp = line;
string item;
string output = ""; 

istringstream iss(exp);

iss >> item;

while(iss)
{
    if(item != "+" && item != "-" && item != "/" && item != "*" && item != "(" && item != ")") //If the char is a number
    {
        cout << item << endl;
    }
    else if(myStack.size() == 0) // If the stack is empty
    {
        myStack.push(item);
    }
    else if( item == "+" || item == "-" || item == "/" || item == "*") //If the char is an operator
    {
        if(priority(myStack.top()) < priority(item)) // the item on the stack is greater priority than the array item
        {
            myStack.push(item);
        }
        else
        {
            while(myStack.size() > 0 && priority(myStack.top()) >= priority(item)) //while the stack contains something, and the item on 
            {           
                string dpu = myStack.top();
                myStack.pop();
                output = output + dpu + " "; 
            }
            myStack.push(item);
        }
    }
    else if(item == "(") // left peren
    {
        myStack.push(item);
    }
    else if(item == ")") // right peren
    {
        while(myStack.top() != "(")
        {
            string dpu = myStack.top();  
            myStack.pop();
            output = output + dpu + " "; 
        }
        myStack.pop();
    }
    iss>> item; 
}
while (myStack.size() > 0 )
{
    string dpu = myStack.top(); 
    output = output + dpu + " ";
    myStack.pop();
}
cout<< output << endl;
}

1 个答案:

答案 0 :(得分:1)

嗯......在你的代码中,数字总是先打印出来:

if (item != "+" && item != "-" && item != "/" && item != "*" && item != "(" && item != ")") //If the char is a number
{
    cout << item << endl;
}

我不熟悉你要求的符号,但是堆栈在我看来并不是这个任务的正确数据结构...使用树似乎对我更好,因为你正在解析