c++ - 简单的数学表达式解析器 (c++)

标签 c++

最终,我要做的是从字符串(即 "((1+2)-3*45)")解析数学表达式,将其构建为二叉表达式树。然而,以下代码片段的目的只是将字符解析为字符串数组,以便将多位整数的各个数字分组到同一索引中。

之后我计划根据括号的位置将该数组转换为后修复表示法并从那里构建,但这不是重点。

我希望 "((1+2)-3*45)"变成 [ "(", "(", "1", "+", "2", ")", "-", "3", "*", "45", ")"]

这是代码,我似乎找不到问题。它编译正常但崩溃。 VS2010 调试器没有显示崩溃发生在哪一行。

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

string* tester(string theString)
{
bool isLastDigit = false;
string* stringArray = new string;
int wheresLast = -1;

for (int i = 0; i < signed int(theString.length()); i++)
{
    if (isdigit(theString[i]) || theString[i]=='.')//if theString[i] is a part of number
        if(isLastDigit)//if the previous char is also a part of a number
            stringArray[wheresLast] += theString[i];
        else//the previous char is not part of a number
        {
            isLastDigit = true;//the last digit will now have been numerical
            stringArray[i] = theString[i];
            wheresLast++;//move on to the next element to fill
        }

    else//if theString[i] is not a part of a number
    {
        isLastDigit = false;//the last digit will now have been non-numerical
        stringArray[i] = theString[i];
        wheresLast++;//move on to the next element to fill
    }
}
return stringArray;
}

void print(string* stringArray, int length)
{
    for(int j = 0; j < length; j++)
        cout << stringArray[j] << endl;
}

void main(void)
{
    string* k;
    k = tester("((12+4)/(2*3))");
    print(k, 14);
}

最佳答案

您将 stringArray 用作数组,但它实际上只是一个元素。

最好的方法是使用 std::vector 而不是 C 风格的数组。换句话说替换

string* stringArray = new string;

vector<string> stringArray;

并在您的程序使用 stringArray 的其他地方进行适当的更改。网上有大量关于如何使用 std::vector 的教程。

关于c++ - 简单的数学表达式解析器 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19915282/

相关文章:

c++ - 我在哪里可以找到 arm-wince-pe-gcc 的二进制文件?

c++ - 修改对数曲线上的值

c++ - 类型之间是否有类型特征检查包含?

c++ - 是否在特定实现上定义了两个数组之间的指针差异?

C++ 矩阵转置。 boost uBLAS 和双*?

c++ - 在类中创建函数的问题

c++ - C++ 中的变量定义,定义 3 个变量?

c++ - 向条件语句添加条件

c++ - OpenMP 4 中的任务依赖性

C++ Vector,从另一个线程崩溃的 push_back?