利用STL栈将中缀表达式转换成后缀表达式输出

本文详细介绍了C++中运算符的优先级与结合性规则,通过实例展示了如何正确解析表达式,确保计算结果的准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <stack>
#include <string>
using namespace std;
int isp(char ch)
{
    switch(ch)
    {
        case'#':return 0;
        case'(':return 1;
        case'*':
        case'/':
        case'%':
            return 5;
        case'+':
        case'-':
                return 3;
        case')':
            return 6;
    }
}
int icp(char ch)
{
    switch(ch)
    {
        case'#':return    0;
        case'(':return 6;
        case'*':
        case'/':
        case'%':
            return 4;
        case'+':
        case'-':
                return 2;
        case')':
            return 1;
    }
}
int main()
{
    stack<string> x;
    stack<char>   s;
    char ch1='#';
    double operand;
    s.push(ch1);
    cin.get(ch1);
    while(!s.empty()&&ch1!='#')
    {
        if(isdigit(ch1)) {cin.putback(ch1);cin>>operand;(cout<<operand<<" ";cin.get(ch1);}            //判断是否是数字,若是数字,则输出
        else {
            if(icp(ch1)>isp(s.top())) {s.push(ch1);cin.get(ch1);}    //如果栈外icp>栈内isp  ,压栈且读入下一个字符
            else if(icp(ch1)<isp(s.top())){cout<<s.top()<<" ";s.pop();}     //如果栈外icp<栈内isp,输出栈顶元素并退栈
            else if(icp(ch1)==isp(s.top())){                     //如果icp>isp,1--如果栈顶元素为“(”,则退栈,并读入下一个元素
                                                                //              2--如果栈顶元素不为“(”,仅仅退栈;
                if(s.top()=='(') cin.get(ch1);
                s.pop();
            }
        }


    }
    cout<<"循环结束"<<endl;
        //cout<<s.top()<<endl;
        cin.get();

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值