C++ 前缀括号的中缀

C++ 前缀括号的中缀,c++,algorithm,prefix,infix-notation,postfix-notation,C++,Algorithm,Prefix,Infix Notation,Postfix Notation,如何将其转换为接受括号的位置,目前唯一可以使用的是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

如何将其转换为接受括号的位置,目前唯一可以使用的是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;
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
整数优先级(字符a)
{
内部温度;
如果(a='*'| | a='/'| | a=='%'))
温度=2;
else如果(a=='+'| | a=='-')
温度=1;
返回温度;
}
//开始
int main()
{
//声明一个名为“中缀”的字符串
字符串中缀;
串流输出;
堆栈s1、s2;
cout优先级(中缀[i]))
{       

输出您正在寻找反向波兰符号

以下是参考资料-

你可以获得链接和阅读材料来实现它


顺便说一句-不要在6502汇编程序中执行此操作-这是一场噩梦!

正如您指出的,您打算从中缀转换为前缀表示法。 不幸的是,你的任务并不像跳过一些括号那么简单

与无括号的前缀表示法不同,中缀表示法要求它们任意描述您想要执行的任何可能的计算

以此为例:

(1 + 2) / (3 + 4)
虽然这可以很好地写为

 / + 1 2 + 3 4
在前缀表示法中,如果没有任何括号,就无法用中缀表示法表示相同的计算

与其尝试依次分析每一个操作,还需要一个完整的解析器以中缀符号构建字符串的解析树

否则就没有机会正确计算

  (1 + 2 * ( 3 / (4 + 3) * 48 + (81 / 4)) + 8) - 9
比如说

与您的问题相关的术语,您可能希望对其进行调查,通常称为表达式语法


看看这里的例子:(见:)

反向波兰符号是后缀,不是吗?这是中缀prefix@user2206227-好吧,那么只需以相反的顺序阅读堆栈,将后缀更改为前缀。你完全正确-反向波兰语完全是胡说八道。然而,镜像符号不会更改上面的任何语句。我无论如何都会修复它们。请参见波兰语notation——Reverse使用的事实是,需要存储在堆栈上的只有数字。运算符从堆栈上取下东西,进行计算,并将结果放在堆栈上。Polish还需要在堆栈上记录运算符,因此,区分部分结果和运算符有点困难。