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

My mathematical expression converter doesn't print correctly

本文关键字:打印 转换器 表达式 我的      更新时间:2023-10-16

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

这个语句的实际输出5 - ( 2 * 3 ) + 55 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;
}

嗯…在您的代码中,数字总是在其他内容之前打印:

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

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