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.
To use the atof()
function, include the following library:
#include <cstdlib>
The atof()
function can be declared as follows:
double atof(const char* str);
str
: The string that is converted to a floating-point number.The atof()
function returns a double
type variable that is the floating-point interpretation of the string str
.
The
atof()
function returns0
if :
str
is empty.str
contains only whitespace characters.- The sequence of non-whitespace characters in
str
is not a valid floating-point number.
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;}
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.
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;}
Three strings, str1
, str2
, and str3
, are declared in lines 8-10.
atof()
function to convert str1
to a floating-point number. The atof()
function returns 0
, as str1
is empty.atof()
function to convert str2
to a floating-point number. The atof()
function returns 0
, as str2
only contains whitespace characters.atof()
function to convert str3
to a floating-point number. The atof()
function returns 0
, as non-whitespace characters of str3
do not represent a valid-floating point number.Free Resources