strtod() function in C++

In this guide, you will learn what is strtod() function is in C++ programming and how to use it with an example.

1. strtod() Function Overview

The strtod() function, included in the C++ standard library <cstdlib>, converts a C-style string to a double. It interprets the content of the string as a floating-point number and returns its value. The function also provides a way to detect errors or invalid inputs by using an additional argument.

Signature:

double strtod(const char* str, char** endptr);

Parameters:

- str: A pointer to the null-terminated string that needs to be converted to a double.

- endptr: A pointer to a char* that will point to the first invalid character encountered, or the terminating null character if the entire string is valid.

2. Source Code Example

#include <iostream>
#include <cstdlib>

int main() {
    const char* float_str1 = "3.1415926535 extra";
    const char* float_str2 = "-2.71828 more text";
    char* endPtr;

    double num1 = strtod(float_str1, &endPtr);
    double num2 = strtod(float_str2, &endPtr);

    std::cout << "String: " << float_str1 << " as Double: " << num1 << std::endl;
    std::cout << "End at: " << endPtr << std::endl;

    std::cout << "String: " << float_str2 << " as Double: " << num2 << std::endl;
    std::cout << "End at: " << endPtr << std::endl;

    return 0;
}

Output:

String: 3.1415926535 extra as Double: 3.1415926535
End at: extra
String: -2.71828 more text as Double: -2.71828
End at: more text

3. Explanation

1. We have two strings: float_str1 and float_str2 which both contain valid double numbers followed by some additional text.

2. The strtod() function is called with each of these strings and the address of endPtr as its arguments.

3. The function converts the valid part of the string into a double and sets endPtr to point to the first invalid character it encounters.

4. The output shows the values of the converted doubles as well as the content pointed to by endPtr, indicating where the conversion ended.

5. This function is especially useful when error detection or more precise parsing is required. If the initial part of the string does not form a valid number, the function returns 0.0, and endPtr will point to the original str.


Comments