Answer: Following two functions take string as arguments and convert them into double values.
double atof(char const *string); double strtod(char const *string, char **ptr2loc);
These are defined in ‘stdlib.h’ header. Notice that if second argument to ‘strtod()’ function is not NULL then it points to location where is saved pointer-to-first-character in non-converted part of string. If string argument doesn’t contain valid numeric value, both functions return ZERO. Also, any leading white space characters in the string argument are skipped by each function. Let’s see an example C program below
/* fp_str_con.c -- string conversion functions return double values */ /* double atof(char const *string) */ /* double strtod(char const *string, char **p2cs) */ #include <stdio.h> #include <stdlib.h> #define SIZE 100 int main(void) { char string[SIZE]; double ret; char **p2unused; /* read some string from the user */ printf("User, type in some string with legal numeric value " "within it...\n"); gets(string); /* atof() takes just string argument */ ret = atof(string); printf("String \"%s\" converted to: %lf\n", string, ret); /* call strtod() to convert string to double value */ ret = strtod(string, p2unused); printf("String \"%s\" converted to: %lf\n", string, ret); printf("Part of \"%s\" not converted:\"%s\"\n", string, *p2unused); return 0; }
Output for some arbitrary values as follows
User, type in some string with legal numeric value... 23.9 hello dear String " 23.9 hello dear" converted to: 23.900000 String " 23.9 hello dear" converted to: 23.900000 return 0; } Output for some arbitrary values as follows <pre lang="C" cssfile="hk1_style"> User, type in some string with legal numeric value... 23.9 hello dear String " 23.9 hello dear" converted to: 23.900000 String " 23.9 hello dear" converted to: 23.900000 Part of " 23.9 hello dear" not converted: " hello dear" User, type in some string with legal numeric value... where are you? 123 String "where are you? 123" converted to: 0.000000 String "where are you? 123" converted to: 0.000000 Part of "where are you? 123" not converted: "where are you? 123" User, type in some string with legal numeric value... 23e-05 why this? String "23e-05 why this?" converted to: 0.000230 String "23e-05 why this?" converted to: 0.000230 Part of "23e-05 why this?" not converted: " why this?"
Notice that any leading white space characters were skipped while trailing illegal characters after valid numeric value were ignored.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Apply for C Internship
- Watch Advanced C Programming Videos
- Practice Computer Science MCQs
- Apply for Computer Science Internship
- Check Computer Science Books