#include<stdio.h>
int strtoval(char pst[], double* p)
{
int sucs;
int plus;
int i = 0;
double frac = 0.1;
*p = 0.0;
while (pst[i] == ' ') i++;
if (pst[i] == '+' || pst[i] >= '0' && pst[i] <= '9')
{
plus = 1;
sucs = 1;
}
else if (pst[i] == '-')
{
plus = 0;
sucs = 1;
}
else
{
sucs = 0;
return sucs;
}
if (pst[i] == '+' || pst[i] == '-')
i++;
if (pst[i] == ' ')
i++;
if (!(pst[i] >= '0' && pst[i] <= '9'))
{
sucs = 0;
return sucs;
}
while (pst[i] != '\0')
{
if (pst[i] >= '0' && pst[i] <= '9')
{
*p = *p * 10 + pst[i] - '0';
i++;
}
else if (pst[i] == '.')
break;
else
{
if (plus == 0)
*p = -1.0 * *p;
return sucs;
}
}
if (pst[i] == '.')
{
i++;
while (pst[i] != '\0')
{
if (pst[i] >= '0' && pst[i] <= '9')
{
*p = *p + (pst[i] - '0') * frac;
frac /= 10;
i++;
}
else
{
if (plus == 0)
*p = -1.0 * *p;
return sucs;
}
}
return sucs;
}
return sucs;
}
void main()
{
char str[][100] = {
" +a12345.09a",
" -32-3",
" 56.76a",
" + 283.-125",
" +a8.6"
};
double a;
int i;
for (i = 0; i < 5; i++)
if (strtoval(str[i], &a) == 1)
printf("vol=%f\n", a);
else
printf("error,the string is %s\n", str[i]);
}
输出结果: