超简单计算器的C++实现,只支持加减乘除和括号

#include <string>
#include <iostream>
#include <stack>
#include <vector>
#include <map>
#include <assert.h>
using namespace std;

string strip(const string &s, const string &chars = "")
{
    if (s.empty())
        return s; 
    
    string s1 = s;
    if (chars.empty()) //默认为空字符
    {
        string::iterator siter = s1.begin();  
        while (siter != s1.end())
        {
            if (isspace(*siter))
                siter = s1.erase(siter);
            else
                break;
        }
 
        if (s1.empty())
            return s1;
 
        siter = s1.end();
        while (siter != s1.begin())
        {
            if (isspace(*--siter))
                siter = s1.erase(siter);
            else
                break;
        }
    }
    else
    {
        string::iterator siter = s1.begin();  
        while (siter != s1.end())
        {
            if (chars.find(*siter) != string::npos)
                siter = s1.erase(siter);
            else
                break;
        }
 
        if (s1.empty())
            return s1;
 
        siter = s1.end();
        while (siter != s1.begin())
        {
            if (chars.find(*--siter) != string::npos)
                siter = s1.erase(siter);
            else
                break;
        }
    }
 
    return s1;  
}

vector<string> get_infix_exp(string expr)
{
    vector<string> infix_exp;
    string::size_type n;
    while ((n = expr.find_first_of("+-*/()")) != string::npos)
    {
        if (!strip(expr.substr(0, n)).empty())
            infix_exp.push_back(strip(expr.substr(0, n)));
        infix_exp.push_back(expr.substr(n, 1));
        expr = expr.substr(n+1);
    }
    if (!strip(expr).empty())
        infix_exp.push_back(strip(expr));
    // for (const auto &s :infix_exp)
    // {
    //     cout << "[" <<s << "] ";
    // }
    // cout << endl;
    
    return infix_exp;
}

vector<string> get_postfix_exp(const vector<string> &infix_exp)
{
    //运算符的优先级,优先级,值越大优先级越低
    map<string, int> operator_pri = {{"+", 2}, {"-", 2}, {"*", 1}, {"/", 1}, {"(", 3}, {")", 0}};
    stack<string> calc_stack;
    vector<string> postfix_exp;
    //获取后缀表达式
    for (const auto &s : infix_exp)
    {
        if (isdigit(s[0]))
        {
            postfix_exp.push_back(s);
        }
        else if (s[0] == '(')
        {
            calc_stack.push(s);
        }
        else if (s[0] == ')')
        {
            while (!calc_stack.empty())
            {
                string s1 = calc_stack.top();
                if (s1 != "(")
                    postfix_exp.push_back(s1);
                calc_stack.pop();
            }
        }
        else
        {
            while (!calc_stack.empty())
            {
                if (operator_pri[s] >= operator_pri[calc_stack.top()])
                {
                    postfix_exp.push_back(calc_stack.top());
                    calc_stack.pop();
                }
                else
                {
                    break;
                }
            }
            calc_stack.push(s);
        }
    }

    while (!calc_stack.empty())
    {
        postfix_exp.push_back(calc_stack.top());
        calc_stack.pop();
    }
    // for (const auto &s :postfix_exp)
    // {
    //     cout << "[" <<s << "] ";
    // }
    // cout << endl;

    return postfix_exp;
}

int get_result(const vector<string> &postfix_exp)
{
    stack<string> calc_stack;
    for (const auto &s : postfix_exp)
    {
        if (isdigit(s[0]))
        {
            calc_stack.push(s);
        }
        else
        {
            int i = stoi(calc_stack.top());
            calc_stack.pop();
            int j = stoi(calc_stack.top());
            calc_stack.pop();
            int k;
            if (s == "+")
            {
                k = j + i;
            }
            else if (s == "-")
            {
                k = j - i;
            }
            else if (s == "*")
            {
                k = j * i;
            }
            else if (s == "/")
            {
                k = j / i;
            }
            calc_stack.push(to_string(k));
        }
    }

    return stoi(calc_stack.top());
}

int calc(string expr)
{
    //获取中缀表达式
    vector<string> infix_exp = get_infix_exp(expr);
    //获取后缀表达式
    vector<string> postfix_exp = get_postfix_exp(infix_exp);
    //计算结果
    return get_result(postfix_exp);
}

// 输入表达式  "1+2*3-4", 只支持加减乘除
/*
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("%s exp\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    cout << "result = " << calc(argv[1]) << endl;
}
*/
//test
int main()
{
    string expr1 = "1+2+3*2/2-1-2";
    string expr2 = "1   +  2   + 3 * 2 / 2 - 1 -  2";
    int result = 1+2+3*2/2-1-2;
    assert(result == calc(expr1));
    assert(result == calc(expr2));

    string expr3 = "(1234 + 5678) / (5678 + 1234)";
    result = (1234 + 5678) / (5678 + 1234);
    assert(result == calc(expr3));

    string expr4 = "((12 * 34) - (11 * 24 + 56)) / 4";
    result = ((12 * 34) - (11 * 24 + 56)) / 4;
    assert(result == calc(expr4));
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值