YouTip LogoYouTip

C Function Strtod

## C Library Function - `strtod()` The `strtod()` function is a built-in C library function declared in the `` header file. It is used to convert a character string representation of a floating-point number into a double-precision floating-point value (`double`). Compared to simpler conversion functions like `atof()`, `strtod()` is much more robust because it provides error detection and allows you to identify where the numeric conversion stopped within the input string. --- ## Syntax and Declaration The prototype for the `strtod()` function is as follows: ```c double strtod(const char *str, char **endptr); ``` ### Parameters * **`str`**: A pointer to the null-terminated string that you want to convert into a double-precision floating-point number. * **`endptr`**: A pointer to a pointer to a character (`char**`). * If `endptr` is not `NULL`, the function stores the address of the first character *after* the converted numerical part in the location referenced by `endptr`. * If `endptr` is `NULL`, this parameter is ignored, and no pointer is returned. ### Return Value * **Success**: Returns the converted double-precision floating-point value. * **No Conversion Possible**: If no valid conversion could be performed, the function returns `0.0`. * **Out of Range**: * If the correct value is outside the range of representable values for a `double`, a positive or negative `HUGE_VAL` is returned, and the global variable `errno` is set to `ERANGE`. * If the correct value would cause an underflow, the function returns `0.0` and sets `errno` to `ERANGE`. --- ## How `strtod()` Works The function parses the input string `str` in the following sequence: 1. **Leading Whitespace**: It skips any leading whitespace characters (spaces, tabs, newlines, etc.). 2. **Sign**: It optionally accepts a plus (`+`) or minus (`-`) sign. 3. **Numeric Value**: It matches a sequence of digits optionally containing a decimal point, optionally followed by an exponent (e.g., `e` or `E` followed by a signed integer). It also supports hexadecimal floats (prefixed with `0x` or `0X`) and special values like `INF`, `INFINITY`, `NAN`, and `NAN(...)` (case-insensitive). 4. **Stopping Point**: It stops reading the string at the first character that cannot be interpreted as part of a floating-point number. The pointer to this character is stored in `endptr`. --- ## Code Examples ### Example 1: Basic Usage and String Splitting This example demonstrates how to convert a string containing a number followed by text, and how to capture the remaining text using `endptr`. ```c #include #include int main() { char str = "20.30300 This is a test"; char *ptr; double ret; // Convert the string to double ret = strtod(str, &ptr); // Output the results printf("The number (double) is: %lf\n", ret); printf("The remaining string part is: |%s|\n", ptr); return 0; } ``` #### Output ```text The number (double) is: 20.303000 The remaining string part is: | This is a test| ``` --- ### Example 2: Robust Error Handling and Multiple Conversions This example demonstrates how to use `strtod()` to parse multiple numbers from a single string and handle potential conversion errors. ```c #include #include #include int main() { const char *str = "3.14159 -2.5e3 invalid_number 99.9"; char *next_part; printf("Parsing string: \"%s\"\n\n", str); // 1. Parse first number (3.14159) double val1 = strtod(str, &next_part); printf("Parsed value 1: %f\n", val1); // 2. Parse second number (-2.5e3 = -2500.0) double val2 = strtod(next_part, &next_part); printf("Parsed value 2: %f\n", val2); // 3. Attempt to parse invalid sequence ("invalid_number") char *error_check; double val3 = strtod(next_part, &error_check); // If error_check points to the same address as next_part, no conversion occurred if (next_part == error_check) { printf("Parsing failed at: \"%s\"\n", error_check); } else { printf("Parsed value 3: %f\n", val3); } return 0; } ``` #### Output ```text Parsing string: "3.14159 -2.5e3 invalid_number 99.9" Parsed value 1: 3.141590 Parsed value 2: -2500.000000 Parsing failed at: " invalid_number 99.9" ``` --- ## Considerations & Best Practices 1. **Prefer `strtod()` over `atof()`**: While `atof(str)` is simpler, it returns `0.0` on failure, making it impossible to distinguish between a failed conversion and a successfully parsed `0.0`. `strtod()` solves this by using the `endptr` parameter to verify if any characters were actually processed. 2. **Checking for Successful Conversion**: To ensure a conversion was successful, check if `str` and `endptr` point to different locations: ```c char *end; double val = strtod(str, &end); if (str == end) { // No conversion could be performed } ``` 3. **Handling Overflow/Underflow**: Always check `errno` against `ERANGE` if you are dealing with extreme inputs that might exceed the limits of a double-precision float. Remember to include ``.
← C Function StrtolC Function Atol β†’