中綴表達式轉後綴表達式

自己寫的爛代碼,可能bug百出,並且只能計算10以內的數。先記錄一下

#include<iostream>
#include<cstdio>
#include<stack>
#include<string>
using namespace std;
stack<char> ss;
int main()
{
    char s[100];
    char s1[100];
    memset(s1,0,sizeof(s1));
    while(cin>>s)
    {
        getchar();
        cout<<s<<endl;
        int t=0;
        int judge=0;
        for(int i=0;s[i]!='\0';i++)
        {
            if(s[i]>='0'&&s[i]<='9')
                s1[t++]=s[i];
            else
            {
                if(s[i]=='(')
                {
                    ss.push(s[i]);
                    continue;
                }
                else if(s[i]==')')
                {
                    while(ss.top()!='(')
                    {
                        s1[t++]=ss.top();
                        ss.pop();
                    }
                    ss.pop();
                }
                else if(s[i]=='*'||s[i]=='/')
                {
                    while(!ss.empty())
                    {
                        if(ss.top()=='*'||ss.top()=='/')
                        {
                            s1[t++]=ss.top();
                            ss.pop();
                        }
                        else break;
                    }
                    ss.push(s[i]);
                }
                else
                {
                    while(!ss.empty())
                    {
                        if(ss.top()!='(')
                        {
                            s1[t++]=ss.top();
                            ss.pop();
                        }
                        else break;
                    }
                    ss.push(s[i]);
                }
            }
        }
        while(!ss.empty())
        {
            s1[t++]=ss.top();
            ss.pop();
        }
        cout<<s1<<endl;
        cout<<"********"<<endl;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章