atof() function in C++

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

1. atof() Function Overview

The atof() function, which is a part of the C++ standard library <cstdlib>, converts a C-style string into a double. It interprets the content of the string as a floating-point number and returns its value as a double. If the conversion cannot be performed, it returns 0.0.

Signature:

double atof(const char* str);

Parameters:

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

2. Source Code Example

#include <iostream>
#include <cstdlib>

int main() {
    const char* float_str1 = "3.1415926535";
    const char* float_str2 = "-2.71828";
    const char* invalid_str = "123.456abc";

    double num1 = atof(float_str1);
    double num2 = atof(float_str2);
    double invalid_num = atof(invalid_str);

    std::cout << "String: " << float_str1 << " as Double: " << num1 << std::endl;
    std::cout << "String: " << float_str2 << " as Double: " << num2 << std::endl;
    std::cout << "String: " << invalid_str << " as Double: " << invalid_num << std::endl;

    return 0;
}

Output:

String: 3.1415926535 as Double: 3.1415926535
String: -2.71828 as Double: -2.71828
String: 123.456abc as Double: 123.456

3. Explanation

1. We have three strings: float_str1, float_str2, and invalid_str. The first two strings represent valid double numbers, while the third string contains a mix of numbers and characters.

2. The atof() function converts each of these strings into a double.

3. When it comes to the invalid_str, atof() stops reading the string once it encounters the first character which isn't a valid part of a floating-point number.

4. The output demonstrates the values of the converted doubles.

Note: Just like with atol(), one should exercise caution when utilizing atof(). It doesn't explicitly report errors and may produce unintended results for certain inputs. For robust error handling and checking, consider using alternatives such as std::stod which provides exceptions on invalid input.


Comments