c++ - C++字符串表达式求解器运行冲突

标签 c++ error-handling expression access-violation

我正在尝试创建一个将使用表达式(例如:“10 * 2 + 1”)的程序并对其进行求解。我的代码是:

#include <iostream>
#include <string>
#include <vector>

void calculateString(std::string str);

int main() {

    calculateString("10*2+2");

    system("pause");
}

void calculateString(std::string str) {
    int total = 0;
    std::string temp1 = "";
    std::string temp2 = "";
    std::string add = "";
    std::string *ray = new std::string[str.length()];
    std::vector<int> newRay;

    for (int i = 0; i < str.length(); i++) {
        if (str.at(i) != '*' && str.at(i) != '/' && str.at(i) != '+' && str.at(i) != '-') {
            add += str.at(i);
        }
        else {
            ray[i] = add;
            std::cout << ray[i] << "\n";
            add = "";
        }
    }
    for (int i = 0; i < str.length(); i++) {
        if (ray[i].compare("*")) {
            total = atoi(ray[i - 1].c_str()) * atoi(ray[i + 1].c_str());
            newRay.push_back(total);
        }
    }
    for (int i = 0; i < str.length(); i++) {
        if (ray[i] == "+") {
            newRay.push_back(atoi(ray[i - 1].c_str()) + atoi(ray[i + 1].c_str()));
        }
    }
    for (int i = 0; i < newRay.size(); i++) {
        std::cout << newRay[i] << "\n";
        total += newRay[i];
    }
    std::cout << str << "=" << total << "\n";
}

但是,每当我运行此命令时,我都会遇到以下访问冲突错误:

Exception thrown at 0x0F1CD4A0 (ucrtbased.dll) in CalcString.exe: 0xC0000005: Access violation reading location 0x01BE0FEE.



它指向第34行,这是:total = atoi(ray[i - 1].c_str()) * atoi(ray[i + 1].c_str());这基本上是在计算表达式的乘法部分,然后将asnwer存储在一个变量中。我已经尝试了所有方法,从将数组更改为 vector 到尝试重写所有方法,似乎没有任何效果。请帮忙

最佳答案


if (ray[i].compare("*"))

比较被滥用。 According to cppreference compare返回小于等于0,等于等于0,大于等于0。作为if条件,0为false,其他所有条件为true,因此这解析为
if (ray[i] != "*")

可能与期望的相反。

if为“10”且ray[0]为0时,这允许进入i的主体,从而导致
total = atoi(ray[0 - 1].c_str()) * atoi(ray[0 + 1].c_str());

要么
total = atoi(ray[-1].c_str()) * atoi(ray[1].c_str());

并且访问负数组索引是未定义的行为。在这种情况下看起来像是崩溃。

解:

在这种情况下,我们关心的只是平等,因此我们可以摆脱
if (ray[i] == "*")

就像做的一样
if (ray[i] == "+")

我还建议检查一下以确保运算符绝不是ray的第一个元素。

关于c++ - C++字符串表达式求解器运行冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41884964/

相关文章:

c++ - 在可变模板参数上实现数学补码逻辑

go - 为什么建议在 go 中返回 `error` 接口(interface)而不是具体的错误类型?

r - 如何在 R 中定义灵活的 'function expression'

c++ - 从多重继承中确定模板包

c++ - SSE2 内在函数在哪里存储结果?

python - 如何执行200个功能的错误处理?

error-handling - NServiceBus 消息处理程序不会在异常时进入 'error' 队列

javascript - 用于检查输入是否包含字符或至少 1 个笑脸的正则表达式?

regex - 正则表达式中 (?s) 的含义

c++ - 为什么我的 OpenGL 纹理不起作用?