|
From: Per W. <pw...@ia...> - 2003-01-19 20:47:18
|
Hello!
Don't use atof() for converting from text string to a double.
Use strtod() instead, since it will inform you how many characters it
consumed.
char mystring[] =3D "1.2E-3*3";
char *p =3D mystring;
char *end;
num =3D strtod(p,&end);
Now end will point to the '*' character, since '1.2E-3' is consumed and
returned as the double 0.0012.
Note also when parsing infix expressions, that you normally have to take
care of unary signs, i.e. 1+-2 which should be evaluated as 1 + (-2).
Easiest is to perform the parsing with a recursive-descent parser, i.e.
something like:
eval_expr()
return eval_additive()
eval_additive()
while (*p =3D=3D '+' || *p =3D=3D '-')
if (*p =3D=3D '+') {
p++;
n +=3D eval_multiplicative()
} else {
p++;
n -=3D eval_multiplicative()
}
return n;
eval_multiplicative()
n =3D eval_factor()
while (*p =3D=3D '*' || *p =3D=3D '/')
if (*p =3D=3D '*') {
p++;
n *=3D eval_factor();
} else {
p++;
n /=3D eval_factor();
}
return n;
eval_factor()
if (*p =3D=3D =B4+') {p++; return eval_factor(); }
if (*p =3D=3D '-') {p++; return -eval_factor(); }
if (*p =3D=3D '(') {p++; n =3D eval_expr(); if (p !=3D ')') error(); retu=
rn n; }
return number();
Good luck!
/Per W
On Sun, 19 Jan 2003, j b wrote:
>
>
>
> ---------------------------------
> Gesendet von http://mail.yahoo.de.
> Bis zu 100 MB Speicher bei http://premiummail.yahoo.de.
|