Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- strtod
- #include <stdio.h>
- #include <string.h>
- double parse_double(const char *str) {
- char *tmp = 0;
- double result = 0;
- asprintf(&tmp, "%.3s", str);
- result = strtod(tmp, 0);
- free(tmp);
- return result;
- }
- int main(void) {
- printf("%fn", parse_double("1.23")); // 1.2
- printf("%fn", parse_double("1234")); // 123
- printf("%fn", parse_double("0.09")); // 0.0
- return 0;
- }
- #include <stdio.h>
- double parseDouble(const char *str){
- double val = 0;
- int numCharsRead;
- // Handle errors by setting or returning an error flag.
- if(sscanf(str, "%3lf%n", &val, &numCharsRead) != 1){
- puts("Failed to parse double!");
- }
- else if(numCharsRead != 3){
- puts("Read less than three characters!");
- }
- return val;
- }
- int main(){
- printf("%lfn", parseDouble("1.3")); // 1.300000
- printf("%lfn", parseDouble("1.5999")); // 1.500000
- printf("%lfn", parseDouble(".391")); // 0.390000
- printf("%lfn", parseDouble(".3")); // Read less than three characters!n0.300000
- return 0;
- }
- double strtod(const char *nptr, char **endptr);
- /*
- * Same as strtod() but only takes the first n characters into account.
- * Additionally returns 0. and sets errno to EINVAL if 'nptr' is NULL.
- */
- double strntod(const char *nptr, char **endptr, size_t n)
- {
- double result;
- /* perform input validation */
- if (!nptr)
- {
- errno = EINVAL;
- result = 0.;
- if (endptr)
- {
- *endptr = nptr;
- }
- goto lblExit;
- }
- if (strlen(nptr) <= n)
- {
- /* Nothing to truncate: fall back to standard 'strtod()' */
- result = strtod(nptr, endptr);
- }
- else
- {
- /* create working copy of string */
- char * ptmp = strdup(nptr);
- /* Test whether 'strdup()' failed */
- if (!ptmp)
- {
- result = 0.;
- if (endptr)
- {
- *endptr = nptr;
- }
- goto lblExit;
- }
- /* truncate working copy to n characters */
- ptmp[n] = '