The function double strtod(const char *str, char **endptr); converts a string to a floating-point number(double). The strtod function also sets the endptr to point to the first character after the number. The function skips all white-space characters at the beginning of the string until the first non-whitespace character is found. Then it converts the subsequent characters into a floating point number until it encounters a character which is not a number.
Function prototype of strtod
double strtod(const char *str, char **endptr);
- str : A pointer to a string beginning with the representation of a floating-point number.
- endptr : This is a pointer to a pointer of type char, whose value is set by the function to point to the first character after the number.
Return value of strtod
This function returns the converted floating point number as a double value otherwise it returns zero (0.0), If no valid conversion could be performed.
C program using strtod function
The following program shows the use of strtod function for string to floating point number conversion.
#include <stdio.h> #include <stdlib.h> int main(){ char string[100], *ptr; double value; printf("Enter a string\n"); gets(string); /* String to floating point number conversion */ value = strtod(string, &ptr); printf("Double value : %lf\n", value); printf("String after a number(Double) : %s\n", ptr); return 0; }
Output
Enter a string 1234.55techcrashcourse Double value : 1234.550000 String after a number(Double) : techcrashcourse