A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
strtod converts the initial portion of a string to a double. Unlike atof, it provides an end pointer that tells you where the conversion stopped. This lets you detect trailing garbage, partial conversions, and empty inputs. It sets errno to ERANGE on overflow or underflow. It handles leading whitespace, optional sign, decimal point, exponent notation, and hexadecimal floating-point. It is the correct function for parsing floating-point input from files, command-line arguments, and network protocols.
#include <stdio.h>#include <stdlib.h>#include <errno.h>void parse_double(const char *input) {char *endptr;errno = 0;double val = strtod(input, &endptr);printf("Input: \"%s\"\n", input);printf(" Value: %.6f\n", val);printf(" Endptr: \"%s\"\n", endptr);printf(" Consumed: %ld chars\n", endptr - input);if (endptr == input) {printf(" Status: NO CONVERSION\n");} else if (*endptr != '\0') {printf(" Status: TRAILING GARBAGE\n");} else if (errno == ERANGE) {printf(" Status: RANGE ERROR\n");} else {printf(" Status: OK\n");}printf("\n");}int main(void) {parse_double("3.14159");parse_double(" -2.5e3 ");parse_double("42abc");parse_double("not a number");parse_double("1e999");return 0;}
Five inputs, five different outcomes. The end pointer is the diagnostic tool. If it equals the input, nothing was converted. If it points to a non-null character, there is trailing data after the number. If errno is ERANGE, the value overflowed to infinity or underflowed to zero. atof gives you none of this information. It returns 0.0 for both "0" and "garbage", and you cannot tell them apart.
strtod is the robust parser. It tells you what it consumed, what it left behind, and whether the result is in range. Use it instead of atof whenever you need error detection. The same pattern applies to strtol for integers and strtold for long doubles. Next: atof, atoi, and atol, the simple converters that lack error reporting.
Finish the lesson once you have worked through the material. This awards ★ 30 XP.