In this tutorial, you will learn about C programming string conversion library function strtod()
with explanation and example. C strtod()
is the string conversion function that converts a sequence of characters representing a floating-point value to double.
strtod()
is defined under the general utilities library <stdlib.h>
. Therefore, we should insert stdlib.h
before using it in the program.
#include<stdlib.h>
double strtod( const char *sPtr, char **endPtr );
where,
sPtr = string to be converted
endPtr = pointer to the first character from the converted value in the string
strtod()
returns 0
if it’s unable to convert any portion of its first argument to double.
This function ignores any whitespace character encountered at the beginning of the string.
//C string conversion function strtod
#include<stdio.h>
#include<stdlib.h>
int main()
{
//initializing string pointer
const char *sPtr = "40.5% student are pass";
double n; //variable to store converted string
char *endPtr; //char type pointer
n = strtod( sPtr, &endPtr );
printf("Before Converting: \"%s\"\n", sPtr);
printf("\nDouble Value: %.3f and string part: \"%s\"\n", n, endPtr);
return 0;
}
Output
Explanation
In the above example, variable n
is used to store the double value converted from the string sPtr
whereas, endPtr
is assigned the location of the first character from the converted value in the string.