最终,我要做的是从字符串解析数学表达式(即 "((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);
}