What is atof() in C++?
In C++, we can use the atof() function to convert a string to a floating-point value of datatype double. This function interprets the contents of the string as a floating-point number.
Library
To use the atof() function, include the following library:
#include <cstdlib>
Declaration
The atof() function can be declared as follows:
double atof(const char* str);
str: The string that is converted to a floating-point number.
Return value
The atof() function returns a double type variable that is the floating-point interpretation of the string str.
The
atof()function returns0if :
stris empty.strcontains only whitespace characters.- The sequence of non-whitespace characters in
stris not a valid floating-point number.
Code
Example 1
Consider the code snippet below, which demonstrates the use of the atof() function with different string inputs.
#include <cstdlib>#include <iostream>using namespace std;int main(){char str1[] = "123.12";char str2[] = "-123.7";char str3[] = "12.6end with words";char str4[] = "start with words12.0";double asint1 = atof(str1);cout << "atof(" << str1 << ") = " << asint1 << endl;double asint2 = atof(str2);cout << "atof(" << str2 << ") = " << asint2 << endl;double asint3 = atof(str3);cout << "atof(" << str3 << ") = " << asint3 << endl;double asint4 = atof(str4);cout << "atof(" << str4 << ") = " << asint4 << endl;return 0;}
Explanation
Four strings, str1, str2, str3, and str4, are declared in lines 8-11. We use the atof() function in line 13, line 16, line 19, and line 22 to convert str1, str2, str3, and str4 to floating point numbers.
Example 2
Consider to code snippet below, which demonstrates the case when the atof() function returns 0.
#include <cstdlib>#include <iostream>using namespace std;int main(){char str1[] = "";char str2[] = " \t ";char str3[] = "abc";double asint1 = atof(str1);cout << "atof("<< str1 <<") = " << asint1 << endl;double asint2 = atof(str2);cout << "atof(" << str2 << ") = " << asint2 << endl;double asint3 = atof(str3);cout << "atof(" << str3 << ") = " << asint3 << endl;return 0;}
Explanation
Three strings, str1, str2, and str3, are declared in lines 8-10.
- line 12: We use the
atof()function to convertstr1to a floating-point number. Theatof()function returns0, asstr1is empty. - line 15: We use the
atof()function to convertstr2to a floating-point number. Theatof()function returns0, asstr2only contains whitespace characters. - line 18: We use the
atof()function to convertstr3to a floating-point number. Theatof()function returns0, as non-whitespace characters ofstr3do not represent a valid-floating point number.
Free Resources