I'm writing some functions to parse mathematical functions. The below function is a function that takes in a string and the location of an operator (e.g. =-/*) and then gets the number on each side of the operator e.g. the string would be "-394.2 * + 432.32" and you would specify the position of "*" and it would get the number each side.
enum direction {LEFT = -1, RIGHT = 1};
double getOperand (const string& exp, size_t op_pos,enum direction dir)
{
bool start_found = false;
string num; //the string where the number will be stored
for (size_t i = op_pos + dir; (dir == RIGHT) ? i < exp.length() : i >= 0; i+=dir) // move left/right as specified
{
if (!start_found && (isdigit(exp[i]) || exp[i] == '.' || exp[i] == '+' || exp[i] == '-')) // number found
{
start_found = true;
num += exp[i];
continue;
}
if (start_found && (isdigit (exp[i]) || exp[i] == '.')) //add number
{
num += exp[i];
continue;
}
if (start_found && !isdigit(exp[i])) //no longer valid number as must end in a digit
{
if (dir == LEFT && (exp[i] == '+' || exp[i] == '-')) //if moving left can 'end' in a -
{
num += exp[i];
}
break;
}
}
if (dir == LEFT) //reverse string if number on lefthandside of operator
{
for (size_t i = 0; i < num.length()/2; i++)
{
char temp = num[i];
num[i] = num[num.length() - 1 - i];
num[num.length() - 1 - i] = temp;
}
}
return strtd(num);
}
I believe the above works but it seems very ugly to me. Does anyone have any ideas if there are simpler solutions (that don't use advanced libraries e.g. boost). Not expecting anyone to write this for me but just some ideas would be appreciated.