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

时间:2013-11-11 20:27:28

标签: 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);
}

1 个答案:

答案 0 :(得分:3)

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

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

string* stringArray = new string;

vector<string> stringArray;

并在您的程序使用stringArray的其他位置进行适当的更改。网上有很多关于如何使用std::vector的教程。

相关问题