S
santosh
pereges said:I wrote a function for converting a string of doubles of the form
"xxxxxx yyyyyy zzzzz" into three seperate doubles. Can some one please
tell me if I done something wrong here ?
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>
#include <string.h>
int string_to_double(char *s, char **endptr, double *f)
{
int too_big = 0;
errno = 0;
*f = strtod(s, endptr);
too_big = (errno == ERANGE);
if (too_big)
{
fprintf(stderr, "OUT OF RANGE OF REPRESENTABLE VALUES
\n");
return (1);
}
else
{
if (s == *endptr)
{
fprintf(stderr, "CONVERSION OF STRING FAILED
\n");
return (1);
}
}
return (0);
}
int main(void)
{
char s[50], *ptr = NULL;
char *endptr1, *endptr2, *endptr3;
double f1, f2, f3;
int rc;
if (fgets(s, 50, stdin) == NULL)
{
fprintf(stderr, "ERROR IN INPUT STRING\n");
return (1);
Use EXIT_FAILURE instead of 1.
}
if ((ptr = strchr(s, '\n')) != NULL)
{
*ptr = '\0';
}
This isn't necessary.
rc = (string_to_double(s, &endptr1, &f1) == 0) &&
(string_to_double(endptr1, &endptr2, &f2) == 0) &&
(string_to_double(endptr2, &endptr3, &f3) == 0);
if (rc == 1)
{
printf("%f %f %f\n", f1, f2, f3);
}
return (!rc);
}
Other than what I noted, the code is, as far as I can tell, correct and
ought to work for the type of input you described.