C++字符串表达式求解器遇到访问冲突

C++ String Expression Solver Running Into Access Violation

本文关键字:遇到 访问冲突 字符串 表达式 C++      更新时间:2023-10-16

我正在尝试创建一个程序,该程序将接受一个表达式(例如:"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";
}

但是,每当我运行它时,我都会遇到访问冲突错误,内容如下:

在 CalcString.exe 中0x0F1CD4A0 (ucrtbased.dll) 抛出的异常: 0xC0000005:访问违规读取位置0x01BE0FEE。

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

in

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

比较被滥用。根据 cpp首选项compare返回小于<0,等于 0 或大于返回> 0。 作为if条件,0 为假,其他所有内容为真,因此解析为

if (ray[i] != "*")

可能与期望的相反。

这允许在ray[0]为"10"而i为0时进入if的身体,导致

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的第一个元素。