4
Read a floating point number
- #include <ctype.h>
- double atof( char s[] ) {
- double val, pow;
- int i, sign;
- /* skip spaces */
- for ( i = 0; isspace( s[i] ); ++i )
- ;
- /* deal with sign */
- sign = (s[i] == '-') ? -1 : 1;
- if ( s[i] == '+' || s[i] == '-' )
- ++i;
- /* read integer */
- for ( val = 0.0; isdigit( s[i] ); ++i )
- val = 10.0 * val + (s[i] - '0');
- /* decimal point? */
- if ( s[i] == '.' )
- ++i;
- /* read decimals */
- for ( pow = 1.0; isdigit( s[i] ); ++i ) {
- val = 10.0 * val + (s[i] - '0');
- pow *= 10.0;
- }
- return sign * val / pow;
- }
- #if defined( STANDALONE )
- #include <stdio.h>
- int main( void ) {
- char line[ 4096 ];
- while ( fgets( line, sizeof ( line ), stdin ))
- fprintf( stdout, "%f\n", atof( line ));
- return 0;
- }
- #endif
$ gcc -DSTANDALONE -o atof atof.c
$ ./atof
3
3.000000
-3
-3.000000
+3
3.000000
3.1415
3.141500
-3.
-3.000000
3..1415
3.000000
-3+3
-3.000000
+3.1415
3.141500
abc3.1415def
0.000000
^D
Comments