#include<stdio.h>


int main()
{
float f1,f2,f;
double d1,d2,d;
char s1[]="2.0045",s2[]="1.00056";


f1=atof(s1);
f2=atof(s2);
f=f1-f2;


d1=atof(s1);
d2=atof(s2);
d=d1-d2;


printf("\n%s %s",s1,s2);
printf("\n%f %f : %f",f1,f2,f);
printf("\n%ld %ld : %d\n",d1,d2,d);
return 1;
}

Output:

2.0045 1.00056
1271310336.000000 869988544.000000 : 401321792.000000
-67108864 1104343465 : 1870659584

Desired Output:

2.0045 1.00056
2.0045 1.00056 : 1.00394
2.0045 1.00056 : 1.00394

----------------
My botherations:

  1. Why is 'atof' working so strangely??...isnt it suppose to assign the value 2.0045 to f1 and 1.00056 to f2 and compute f??
  2. How else could i do this :sad:

PS: basically im reading a trace file...and performing some arithematic by parsing it.

Dani AI

Generated

The weird numbers are not a bug in atof — they come from undefined behaviour when printing values with the wrong printf format specifiers. In this thread the double results were printed with integer formats (%ld/%d), so printf read the wrong bytes and produced garbage. As suggested, parsing functions like sscanf can work, but the immediate fixes are: print floats/doubles with the proper specifier and use conversion functions that let you detect errors.

Use %f (or %.6f to control decimals) for float/double output and %Lf for long double. atof returns a double and provides no error reporting; prefer strtod/strtof (they give an end-pointer and set errno so you can detect invalid input or overflow). See the standard docs for printf conversions and for atof/strtod: fprintf conversions, atof, .

Example pattern (use this instead of ignoring errors):

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

const char *s1 = "2.0045", *s2 = "1.00056";
char *end;
errno = 0;
double d1 = strtod(s1, &end);
if (end == s1 || errno == ERANGE) { /* handle conversion error */ }
errno = 0;
double d2 = strtod(s2, &end);
if (end == s2 || errno == ERANGE) { /* handle conversion error */ }

printf("%s %s\n", s1, s2);
printf("%.6f %.6f : %.6f\n", d1, d2, d1 - d2);

Practical notes: float arguments to variadic functions are promoted to double, so %f works for both. If you want strict error handling, use strtod/strtof instead of atof or unvalidated sscanf. This will fix the garbled output seen by and make the parsing robust.

Recommended Answers

All 2 Replies

you could use sscanf

Thanxxxxxx!!...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.