中缀到 C++ 中的后缀转换

infix to postfix conversion in c++

本文关键字:后缀 转换 C++ 中缀      更新时间:2023-10-16

所以在这里我有一个中缀到后缀转换的代码。这个想法是发送一个包含中缀公式的字符串,并返回该公式的后缀表示法。操作器+ - * / () [] {}函数tezinaOperacije()如果操作+-则返回 1,如果操作*/则返回 2。否则返回 -1。当您在打开的括号上调用函数时,该函数zatvorenaZagrada()返回右右括号。问题是该函数返回一个空字符串。有人可以帮忙吗?

string infixToPostfix(string& str){
        stack<char> stek;
        string s="";
        for(int i=0; i<str.size(); i++){
            s+=s[i];
        }
        char pre='(';
        string copy="";
        for(int i=0; i<s.size(); i++){
            if(s[i]>='0' && s[i]<='9'){
                if(pre==')' || prei==']' || pre=='}' || pre=='0') throw "wrong";
                char number=s[i];
                copy+=number;
                pre=='0';
            }
            else if(s[i]=='(' || s[i]=='[' || s[i]=='{'){
                        if(pre=='0' || pre==')') throw "Wrong";
                        char sign=s[i];
                        stek.push(sign);
                        pre=sign;
                    }
            else if(s[i]==')' || s[i]==']' || s[i]=='}'){
                char sign=s[i];
                while(!stek.empty() && tezinaOperacije(stek.top())>0){
                    copy+=stek.top();
                    stek.pop();
                }
                if(stek.empty() || sign !=ZatvorenaZagrada(stek.top())) throw "wrong declaration";
                stek.pop();
                pre=sign;
            }
            else if(tezinaOperacije(s[i])>0){
                char sign=s[i];
                if(tezinaOperacije(pre)>0 || pre=='(' || pre=='[' || pre=='{') throw "wrong";
                while(!stek.empty() && tezinaOperacije(stek.top())>=tezinaOperacije(sign)){
                    copy+=stek.top();
                    stek.pop();
                }
                stek.push(sign);
                pre=sign;
            }
        }
        while(!stek.empty()){
            copy+=stek.top();
            stek.pop();
        }
        return copy;
    }

    string s="";
    for(int i=0; i<str.size(); i++){
        s+=s[i];
//---------^  s?
    }

您获得的s为零 ( ''

我想你的意图是

    string s="";
    for(int i=0; i<str.size(); i++){
        s+=str[i];
//---------^^^
    }

s充满零的情况下,以下for

    for(int i=0; i<s.size(); i++){
        if(s[i]>='0' && s[i]<='9'){
          // ...
        }
        else if(s[i]=='(' || s[i]=='[' || s[i]=='{'){
          // ...
        }
        else if(s[i]==')' || s[i]==']' || s[i]=='}'){
          // ...
        }
        else if(tezinaOperacije(s[i])>0){
          // ...
        }
    }

不做任何有用的东西,copy保持空。