Parsing mathematical statements

Hi

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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.

Thanks
Hello rozick1,

If you want to use a string stream as rjphares suggested your function could shorten to this:

1
2
3
4
5
6
7
8
9
10
11
12
#include <sstream>


void getOperand(const std::string& exp, double& num1, double& num2)
{
	std::string equ{ "-394.2 * +432.3" };
	std::istringstream ss(equ);
	char opp{};
	;
	
	ss >> num1 >> opp >> num2;
}


If the '+' is part of "432.3" then you need to take out the space between the '+' and the '4'.

If you need something more along the lines of what you have I can work on that. Let me know

Hope that helps,

Andy

Edit: forgot to remove a pair of {}.
Last edited on
Topic archived. No new replies allowed.