简体   繁体   中英

Simple Mathematical Expression Parser (c++)

Ultimately what I'm trying to do is parse a mathematical expression from a string (ie "((1+2)-3*45)" ) to build it into a binary expression tree. However, the purpose of the following code snippet is only to parse the characters into an array of strings so as to group the individual digits of multiple-digit integers into the same index.

After that I plan to convert that array into post fix notation based on the location of the parentheses and build from there, but that's beside the point.

I want "((1+2)-3*45)" to become [ "(", "(", "1", "+", "2", ")", "-", "3", "*", "45", ")" ]

Here's the code, which I can't seem to find a problem with. It compiles fine but crashes. The VS2010 debugger isn't showing me what line the crash occurred at.

#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);
}

You use stringArray as an array but it's really only a single element.

The best way to go is to use a std::vector instead of a C-style array. In other words replace

string* stringArray = new string;

with

vector<string> stringArray;

And make the appropriate changes in the other places your program uses stringArray . There is a ton of tutorials on the web about how to use std::vector .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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