Ok, I found some code that will do it. This code will only evaluate integers though.
Code:
/* eval_expr.c */
int op_plus(int a,int b)
{
return (a+b);
}
int op_moins(int a,int b)
{
return (a-b);
}
int op_div(int a,int b)
{
return (a/b);
}
int op_mul(int a,int b)
{
return (a*b);
}
int op_mod(int a,int b)
{
return (a%b);
}
struct s_op
{
char c;
int p;
int (*f)();
} ;
typedef struct s_op t_op;
t_op op [] =
{
{'+',1,op_plus},
{'-',1,op_moins},
{'/',2,op_div},
{'*',2,op_mul},
{'%',2,op_mod},
{0,0,0}
};
int find_last_op(char *str,int p)
{
int pos;
int i;
int ret;
int par;
ret = -2;
par = 0;
pos = strlen(str)-1;
while (pos>=0)
{
if (str[pos] == ')')
par ++;
if (str[pos] == '(')
par --;
i = 0;
while (!par && op[i].c)
{
if (op[i].c==str[pos])
{
ret = -1;
if (op[i].p==p)
return (pos);
}
i ++;
}
pos --;
}
return (ret);
}
int is_nb(char *str)
{
if (*str=='(')
{
str[strlen(str)-1] = 0;
return (eval_expr_sub(str+1,0));
}
return (atoi(str));
}
int eval_expr_sub(char *str,int p)
{
int pos;
char save;
int nb2;
if ((pos = find_last_op(str,p))==-1)
return (eval_expr_sub(str,p+1));
if (pos==-2)
return (is_nb(str));
nb2 = eval_expr_sub(str+pos+1,p+1);
save = str[pos];
str[pos] = 0;
pos = 0;
while (op[pos].c)
{
if (save==op[pos].c)
return (op[pos].f(eval_expr_sub(str,p),nb2));
pos ++;
}
printf("PB !!!\n");
return (0);
}
int Evaluate(char *str)
{
return (eval_expr_sub(str, 0));
}
All you need to do is call the Evaluate function by passing it the string with what you want it to parse. It will return the value as an integer.
- Sean