4

Read a floating point number

  1. #include <ctype.h>
  2.  
  3. double atof( char s[] ) {
  4.     double val, pow;
  5.     int i, sign;
  6.  
  7.     /* skip spaces */
  8.     for ( i = 0; isspace( s[i] ); ++i )
  9.         ;
  10.     /* deal with sign */
  11.     sign = (s[i] == '-') ? -1 : 1;
  12.     if ( s[i] == '+' || s[i] == '-' )
  13.         ++i;
  14.     /* read integer */
  15.     for ( val = 0.0; isdigit( s[i] ); ++i )
  16.         val = 10.0 * val + (s[i] - '0');
  17.     /* decimal point? */
  18.     if ( s[i] == '.' )
  19.         ++i;
  20.     /* read decimals */
  21.     for ( pow = 1.0; isdigit( s[i] ); ++i ) {
  22.         val = 10.0 * val + (s[i] - '0');
  23.         pow *= 10.0;
  24.     }
  25.  
  26.     return sign * val / pow;
  27. }
  28.  
  29. #if defined( STANDALONE )
  30.  
  31. #include <stdio.h>
  32.  
  33. int main( void ) {
  34.     char line[ 4096 ];
  35.  
  36.     while ( fgets( line, sizeof ( line ), stdin ))
  37.         fprintf( stdout, "%f\n", atof( line ));
  38.        
  39.     return 0;
  40. }
  41.  
  42. #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

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].