C++字符串表达式求解器遇到访问冲突
C++ String Expression Solver Running Into 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";
}
但是,每当我运行它时,我都会遇到访问冲突错误,内容如下:
在 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
的第一个元素。
相关文章:
- 写入位置0x0000000C时发生访问冲突
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 链表中写入访问冲突的未知原因
- C++中的openCV Mat访问冲突
- C++尝试深度复制唯一指针时出现内存访问冲突
- C++ 中动态二维数组的访问冲突
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- 写入访问冲突异常
- 在类 12.exe 中0x7B37FF80 (ucrtbased.dll) 引发异常: 0xC0000005:访问冲突读
- 0xC0000005:访问冲突写入位置0xCDCDCDCD动态分配错误
- 读取访问冲突.这0xCDCDCDCD
- 0xC0000005:访问冲突读取位置 0x00000000. 重载 == 运算符的问题
- 插入数组时违反写访问冲突
- 使用 ReadProcessMemory 获取字符串值的访问冲突
- 尝试通过共享指针使用变量时读取访问冲突
- 堆栈上的 C++ 访问冲突写入异常
- 在尝试使用CUDA分配内存时,我遇到了访问冲突写入位置错误
- 调用基构造函数时遇到问题 - 获取读取访问冲突
- C++字符串表达式求解器遇到访问冲突
- 我在删除指针时遇到读取访问冲突