[英]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. 最终我要做的是从字符串解析数学表达式(即“((1 + 2)-3 * 45)”)将其构建为二进制表达式树。 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", ")" ] 我希望“((1 + 2)-3 * 45)”成为[“(”,“”(“,”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. 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);
}
You use stringArray
as an array but it's really only a single element. 您使用stringArray
作为数组,但它实际上只是一个元素。
The best way to go is to use a std::vector
instead of a C-style array. 最好的方法是使用std::vector
而不是C风格的数组。 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
. 并在程序使用stringArray
的其他地方进行适当的更改。 There is a ton of tutorials on the web about how to use std::vector
. 网上有很多关于如何使用std::vector
的教程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.