atof() Function with Example in C++

C++ atof() function: Here, we are going to learn about the atof() function with example of cstdlib header in C++ programming language.
Submitted by IncludeHelp, on May 26, 2020

C++ atof() function

atof() function is a library function of cstdlib header. It is used to convert the given string value to the double value. It accepts a string containing a floating-point number and returns its double value.

Syntax of atof() function:

C++11:

    double atof (const char* str);

Parameter(s):

  • str – represents a string containing a floating-point number.

Return value:

The return type of this function is double, it returns the double converted value.

Example:

    Input:
    str = "123.456";

    Function call:
    atof(str);

    Output:
    123.456

C++ code to demonstrate the example of atof() function

// C++ code to demonstrate the example of
// atof() function

#include <iostream>
#include <cstdlib>
#include <string.h>
using namespace std;

// main() section
int main()
{
    char str[50];

    strcpy(str, "123.456");
    cout << "atof(\"" << str << "\"): " << atof(str) << endl;

    strcpy(str, "-123.456");
    cout << "atof(\"" << str << "\"): " << atof(str) << endl;

    strcpy(str, "0.123456");
    cout << "atof(\"" << str << "\"): " << atof(str) << endl;

    strcpy(str, "-0.123456");
    cout << "atof(\"" << str << "\"): " << atof(str) << endl;

    strcpy(str, "12345678.123456");
    cout << "atof(\"" << str << "\"): " << atof(str) << endl;

    strcpy(str, "-12345678.123456");
    cout << "atof(\"" << str << "\"): " << atof(str) << endl;

    return 0;
}

Output

atof("123.456"): 123.456
atof("-123.456"): -123.456
atof("0.123456"): 0.123456
atof("-0.123456"): -0.123456
atof("12345678.123456"): 1.23457e+07
atof("-12345678.123456"): -1.23457e+07 

Reference: C++ atof() function



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.