我的数学表达式转换器无法正确打印
My mathematical expression converter doesn't print correctly
所以,我正在编写一个程序,它接受输入(一个数学表达式)并将其转换为后缀符号,然后将其打印出来给用户。当我在简单的数学表达式(即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;
}
嗯…在您的代码中,数字总是在其他内容之前打印:
if (item != "+" && item != "-" && item != "/" && item != "*" && item != "(" && item != ")") //If the char is a number
{
cout << item << endl;
}
我不熟悉你请求的符号,但是堆栈对我来说似乎不是这个任务的正确数据结构…使用树对我来说似乎更好,因为您正在解析
相关文章:
- 转换器练习:跳过 if 语句和 if 语句
- 使用转换器提升 Python 问题 - 静态链接
- 我写的 ASCII 到二进制转换器C++向后显示二进制,如何使其正确显示?
- 十进制到二进制转换器 c++
- 用于 boost::p roperty_tree 的通用枚举转换器
- 为什么我的C++基转换器中出现分段错误?
- 将字节数组转换为对象C++ |C++中的 C# 位转换器
- 英语到摩尔斯电码转换器
- 我用c++做了一个转换器,把英里转换成公里,把公里转换成英里,把赛尔修斯转换成法赫伦海特,把法赫伦海特转换成赛尔修斯
- 使用 Json 转换器反序列化 WCF 服务中的C++字符串
- 十进制,包括负到 32 位二进制转换器
- 标准::映射转换器模板
- 英里到千克转换器练习的小语法错误
- 句子转换器在存在新行的情况下不起作用
- 在C Windows程序中获取A/D转换器示例程序
- ROS中未定义的参考误差到OpenCV图像转换器
- 表达式到C++类类型转换器/类型转换
- 这里怎么了?单位转换器
- 中缀到后缀转换器 + 评估程序正确打印到控制台,但不正确地打印到文本文件
- 我的数学表达式转换器无法正确打印