gpt4 book ai didi

c++ - 前缀括号的中缀

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:02:29 25 4
gpt4 key购买 nike

我如何将其转换为接受括号的位置,目前您唯一可以使用的是 2 + 4 * 7。我无法弄清楚如何忽略括号,例如 (2 + 3) * 7 会读出 * + 2 3 7。有什么帮助谢谢。

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

int priority(char a)
{
int temp;

if (a == '*' || a == '/' || a == '%')
temp = 2;
else if (a == '+' || a == '-')
temp = 1;
return temp;
}

//start
int main()
{
//declare a string called "infix"
string infix;
stringstream output;
stack<char> s1, s2;

cout << "Enter an arithmetic expression with no perenthesis: " << endl;
getline(cin, infix);

//this loops through backwards searching for the operators
for(int i = infix.length() - 1; i >= 0; i--)
{
//check the input against +,-,/,*,%
if (infix[i] == '+' || infix[i] == '-' ||
infix[i] == '*' || infix[i] == '/' || infix[i] == '%')
{
while(!s1.empty() && priority(s1.top()) > priority(infix[i]))
{
output << s1.top();
s2.push(s1.top());
s1.pop();
}

s1.push(infix[i]);
}
// I think i need to add an else if to check for parenthesis
// not sure how
else
{
output << infix[i];
s2.push(infix[i]);
}
}

while(!s1.empty())
{
output << s1.top();
s2.push(s1.top());
s1.pop();
}

cout << "\nAnswer: ";

while(!s2.empty())
{
cout << s2.top();
s2.pop();
}

cout <<"\n\nPress enter to exit" << endl;
}

最佳答案

你正在寻找反向抛光符号

这是一个引用 - http://en.wikipedia.org/wiki/Reverse_polish_notation

您可以获得链接和阅读 Material 来实现它。

顺便说一句 - 不要在 6502 汇编器中这样做 - 这是一场噩梦!

关于c++ - 前缀括号的中缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15697614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com