提取字符串中最长的数学表达式并计算(C++)

#include <iostream>
#include <stack>
#include <string>
#include <regex>
using namespace std;

bool priority(char top, char b){
    if(top == '('){//为左括号
        return false;
    }
    if(top == '-' || top == '+' && b == '*'){
        return false;//高则压栈
    }
    if((top == '+' || top == '-') && (b == '+' || b == '-')){
        return false;
    }
    else{
        return true;//计算
    }
}

void compute(stack<int>& s1, stack<char>& s2){
    int b = s1.top();
    s1.pop();
    int a = s1.top();
    s1.pop();
    char ch = s2.top();
    s2.pop();
    int sum = 0;
    if(ch == '+'){
        sum =  a + b;
    }
    else if(ch == '-'){
        sum = a - b;
    }
    else{
        sum = a*b;
    }
    s1.push(sum);
}

int main() {
    //先找到最长的数学表达式子
    string s;
    getline(cin, s);
    //查找最长合法数学表达式
    regex math("(-?\\d+)([\\*+-]\\d+)*"); // 定义正则表达式,匹配数字和操作符序列
    sregex_iterator it(s.begin(), s.end(), math);//允许遍历一个字符串中所有符合正则表达式的子串
    sregex_iterator end;
    string longstr = "";
    while(it != end){
        if(it->str().size() > longstr.size()){
            longstr = it->str();
        }
        it++;
    }
    longstr = longstr + ')';//加上右括号
    stack<int> arr;
    stack<char> symbol;
    string temp = "";
    symbol.push('(');//先压入左括号
    bool flag = false;//标记是负号还是减号
    for(int i = 0; i < longstr.size(); i++){
        if(longstr[i] >= '0' && longstr[i <='9']){
            temp += longstr[i];
        }
        else if(longstr[i] == ')'){//如果是右括号
            flag = false;//后续的第一个-为负号
            arr.push(stoi(temp));
            temp = "";
            while(symbol.top()!='('){
                compute(arr, symbol);
            }
            symbol.pop();
        }
        else if(longstr[i] == '-'){
            if(!flag){//第一次出现-
                temp += '-';
                flag = true;
            }
            else{//是符号
                arr.push(stoi(temp));
                temp = "";
                while(priority(symbol.top(), longstr[i])){
                    compute(arr, symbol);
                }
                symbol.push(longstr[i]);//不计算,压栈
            }
        }
        else{//是其他符号
            flag = true;//下次遇到的-为符号 
            arr.push(stoi(temp));
            temp = "";
            while(priority(symbol.top(), longstr[i])){
                compute(arr, symbol);
            }
            symbol.push(longstr[i]);
        }
    }
    cout << arr.top() << endl;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值