繁体   English   中英

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

[英]Simple Mathematical Expression Parser (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的教程。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM