atof() - Utility Function
How is Utility function "atof()" used in C++?
How to convert a string to double value?
Explanation
atof() is a Utility Function that converts a string into a double value. The string must contain a valid floating pointer number and the string is terminated by white space, punctuation except periods, characters except "e", "E".
Syntax:
double atof(const char *str);
Example :
#include <cstdlib.h> #include <iostream.h> int main() { char arr[50]; cout << "Enter a valid string with floating number" << endl; cin >> arr; cout<<"Value returned by atof is:: "<< atof(arr) << endl; cout<<"Bytes occupied is::" << sizeof(atof(arr)) << endl; } |
Result :
Enter a valid string with floating number
45.00he
Value returned by atof is:: 45
Bytes occupied is:: 8
In the above example atof() is used to convert a string with a floating point integer, by terminating the string when the character "h" is found. The floating point number alone is converted to a double value.