C++ cstdlib atof function


The C++ <ctsdlib> atof function converts the const char* passed as argument to double type.They are same with the functions found in C <stdlib.h> header.The declaration of the function is shown below.

double atof( const char* x);

Parameters:
x – A const char* type.If the argument passed is a ‘string’ type or ‘string’ variable it is an error.

Return type
double – The string converted to double value is returned.

Some points to note:

i) If the passed argument is a combination of number and non-number characters with the number occurring at the initial part,then only the number is converted to the double type.The non-number char part is neglected.

ii) If the argument passed is only non-number characters then 0 is returned.

iii) It is not possible to obtain the number ‘NaN‘(Not a Number) and ‘±∞‘(infinity) using this function.For this you can use some other function like strtod.

Code example

cout<< “atof( \”23.23\” )=” << atof( “23.23” ) << endl;
<< “atof( \”100.43Number\” )=” << atof( “100.43NUmber” ) << endl;

/*Passing non-convertible string */
cout<< “atof( \”C0nst100\” )=” << atof( “C0nst100” ) << endl;

/*Checking if we can obtain ‘nan’ from ‘atof’,
cout<< “atof( \”nan\” )=” << atof( “nan” ) << endl;

/*Checking the return type */
cout<< “Return type of atof( \”1\” )=” << typeid( atof( “1” ) ) .name() << endl; //include the header <typeinfo> to use the ‘typeid().name( )’ function

Output

atof( “23.23” )= 23.23
atof( “100.43Number” )= 100.43
atof( “C0nst100” )= 0
atof( “nan” )= 0
Return type of atof( “1” )= d (means ‘double’)

If we look at the fourth output the return value is 0,it is not ‘nan‘.This prove that ‘atof’ cannot convert the “nan” string to the value ‘nan’.Like wise if you pass “inf” the returned value is 0,this again shows that we cannot obtain ‘inf'(infinity) using ‘atof’ function.

Link : C++ cmath ‘nan’ myths and conception


 


A more exhaustive code example using ‘atof’ function is shown below.

Link : C++ cmath sinh , sinhf , sinhl function

#include <iostream>
#include <cmath>

using namespace std ;

char* func( )
{
return “2000.000” ;
}

int main( )
{
string st=”3.4″ ;

const char *c[]=”9.912e23″ ;

cout<< “atof(c)=” << atof(c) << endl ;
/* cout<< atof(st) << endl ; //error! */

cout<< “pow( atof( \”23\” ) , atof(“2″) )=” << pow( atof( “23” ) , atof(“2”) ) << endl
<< “sinh( atof( \”34.628\”) )=” << sinh( atof(“34.628”) ) << endl ; //calculate the hyperbolic sine of 34.628

cout<< “atof( func() )=” << atof( func( ) ) << endl ;

cin.get( );
return 0;
}

Output

atof(c)= 9.912e13
pow( atof( “23” ) , atof(“2”) )= 529
sinh( atof(34.628) )= 5.46663e+014
atof( func() )= 2000.000

The ‘pow( atof( “23” ) , atof(“2”) )‘ compute the value of 232.

Link : C++ cmath pow ,powf , powl function


*Side Note

Except for the behavior on error ‘atof’ is equivalent to ,

strtod( nptr , (char **)NULL )