Previous Page
Next Page

strtod, strtof, strtold

Converts a string into a floating-point number

#include <stdlib.h>
double strtod ( const char * restrict s , char ** restrict endptr  );
float  strtof ( const char * restrict s , char ** restrict endptr  );    (C99)
long double strtold ( const char * restrict s , char ** restrict endptr   );  (C99)

The strtod( ) function attempts to interpret the string addressed by its first pointer argument, s, as a floating-point numeric value, and returns the result with the type double. strtof( ) and strold( ) are similar, but return float and long double respectively. Leading whitespace characters are ignored, and the string converted ends with the last character that can be interpreted as part of a floating-point numeral. The second parameter, endptr, is a pointer to a pointer. If its argument value is not a null pointer, then the function stores a pointer to the first character that is not part of the numeral converted in the location addressed by the endptr argument. (The locations that the function reads from and writes to using its restricted pointer parameters must not overlap.) If no conversion is possible, the function returns 0.

If the resulting value exceeds the range of the function's type, then the return value is positive or negative HUGE_VAL (or HUGE_VALF or HUGE_VALL, for the float and long double variants). On an overflow, the errno variable is set to the value of ERANGE ("range error"). If the conversion produces an underflow, the magnitude of the return value is at most the smallest value greater than zero that is representable in the function's return type, and the function may set the errno variable to the value of ERANGE ("range error").

The character sequences that can be interpreted as floating-point numerals depend on the current locale. In all locales, they include those described in the section "Floating-Point Constants" in Chapter 3, and the sequences "infinity" and "nan", without regard to upper- or lowercase.

Example

char in[1024], *this = in, *next = in;
double val;
puts( "Enter some floating-point numbers, please:" );
scanf( "%[^\n]", in );

puts( "Here are the values you entered:" );
while ( 1 )
{
  val = strtod( this, &next );
  if ( next == this )       // Means no conversion was possible.
    break ;
  printf( "\t%g\n", val );
  this = next;              // Try again with the rest of the input string.
}
puts( "Done." );

See Also

atof( ); wcstof( ), wcstod( ) and wcstold( ); strtol( ), strtoul( ), and strtoimax( )


Previous Page
Next Page