Converts a string to a double.
double atof(const char *str );
The string str is converted to a floating-point number (type double).
Any initial whitespace characters are skipped.
The number may consist of an optional sign, a string of digits with an optional decimal character, and an optional e or E followed by a optionally signed exponent.
Conversion stops when the first unrecognized character is reached.
double atof (const char* str);
This function has the following parameter.
The function returns the converted floating point number as a double value.
If no valid conversion could be performed, the function returns zero ( 0.0).
If the converted value would be out of the range of representable values by a double, it causes undefined behavior.
#include <stdio.h> /* printf, fgets */
#include <stdlib.h> /* atof */
#include <math.h> /* sin */
/*w w w . j a v a 2 s .c o m*/
int main (){
double n,m;
double pi=3.1415926535;
char buffer[256];
printf ("Enter degrees: ");
fgets (buffer,256,stdin);
n = atof (buffer);
m = sin (n*pi/180);
printf ("The sine of %f degrees is %f\n" , n, m);
return 0;
}
The code above generates the following result.
#include <stdlib.h>
#include <stdio.h>
// w ww. ja v a2 s . c o m
int main(void){
printf("%g\n", atof(" -0.0000000123junk"));
printf("%g\n", atof("0.012"));
printf("%g\n", atof("15e16"));
printf("%g\n", atof("-0x1afp-2"));
printf("%g\n", atof("inF"));
printf("%g\n", atof("Nan"));
return 0;
}
The code above generates the following result.