You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++如何将包含计算式的字符串转换为运算后的整数结果

问题原因分析

std::stoi的功能仅为解析字符串开头的连续整数序列,仅允许字符串首字符为正负号,遇到其余非数字字符会直接终止解析流程,因此你的示例代码遇到+就停止解析,仅返回了-123,它本身不具备运算表达式解析计算的能力。

解决方案

你需要实现表达式解析逻辑,根据需求复杂度可以选择不同的实现方案:

方案1:仅处理加减乘除整数运算(无括号场景)

可以用栈的思路实现,逻辑如下:

  • 遍历字符串,先提取完整的数字
  • 记录当前数字前的运算符,默认第一个数字前运算符为+
  • 遇到+/-直接将当前数字带符号压栈
  • 遇到*//就弹出栈顶元素和当前数字运算,结果再压栈
  • 遍历结束后将栈中所有元素求和就是最终结果

示例实现代码:

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

int calculate(string s) {
    stack<int> st;
    int num = 0;
    char op = '+'; // 初始默认第一个数前是+
    int n = s.size();
    for (int i = 0; i < n; i++) {
        if (isdigit(s[i])) {
            num = num * 10 + (s[i] - '0');
        }
        // 遇到运算符或者到末尾的时候处理之前的数字和运算符
        if ((!isdigit(s[i]) && s[i] != ' ') || i == n - 1) {
            if (op == '+') st.push(num);
            else if (op == '-') st.push(-num);
            else if (op == '*') {
                int top = st.top();
                st.pop();
                st.push(top * num);
            } else if (op == '/') {
                int top = st.top();
                st.pop();
                st.push(top / num);
            }
            op = s[i];
            num = 0;
        }
    }
    int res = 0;
    while (!st.empty()) {
        res += st.top();
        st.pop();
    }
    return res;
}

int main() {
    string variable1 = "-123+432";
    cout << calculate(variable1) << endl; // 输出309
    string variable2 = "-123+432*2";
    cout << calculate(variable2) << endl; // 输出741
    return 0;
}

方案2:支持任意复杂度运算(含括号、自定义优先级等)

如果需要支持括号、自定义运算符优先级,推荐使用调度场算法(Shunting-yard Algorithm),核心逻辑是将中缀表达式(用户输入的常规表达式)转换为后缀表达式(逆波兰表达式),再计算后缀表达式的结果,这个方案可以适配任意长度、任意复杂度的运算表达式需求。

核心实现步骤:

  1. 预处理输入字符串,去除空格等无效字符
  2. 遍历中缀表达式,分离数字、运算符、括号
  3. 按照运算符优先级、括号规则将表达式转换为后缀表达式
  4. 遍历后缀表达式,用栈完成计算得到最终结果

内容的提问来源于stack exchange,提问作者the technician 274

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 05:15:03