atof() in C
The atof() function converts a C-style string, passed as an argument to atol() function, to double. It converts the C-string str to a value of type double by interpreting the characters of the string as numerical values. It discards the leading whitespace characters until a non-whitespace character is found.
Syntax
double atof ( const char * str );
Parameters
- The function accepts a single mandatory parameter str which is the representation of a floating point number.
Return Value
- The function returns the double value type representation of the string.
- The function returns zero (0.0) if no conversion is performed.
Note: If the C-string str passed to atol() function is either empty or contains only whitespace characters, it is not a valid floating point number, no conversion will be performed and it will return 0.0.
Example: Program to Illustrate the Working of atof() Function.
C
// C program to illustrate // working of atof() function. #include <stdio.h> // Include this header for atof function #include <stdlib.h> int main() { // char array char pi[] = "3.1415926535" ; // Calling function to convert to a double double pi_val = atof (pi); // prints the double value printf ( "Value of pi = %lf\n" , pi_val); // char array char acc_g[] = "9.8" ; // Calling function to convert to a double double acc_g_val = atof (acc_g); // prints the double value printf ( "Value of acceleration due to gravity = %.1lf\n" , acc_g_val); return 0; } |
C++
// CPP program to illustrate // working of atof() function. #include <bits/stdc++.h> using namespace std; int main() { // char array char pi[] = "3.1415926535" ; // Calling function to convert to a double double pi_val = atof (pi); // prints the double value cout << "Value of pi = " << pi_val << "\n" ; // char array char acc_g[] = "9.8" ; // Calling function to convert to a double double acc_g_val = atof (acc_g); // prints the double value cout << "Value of acceleration due to gravity = " << acc_g_val << "\n" ; return 0; } |
Value of pi = 3.14159 Value of acceleration due to gravity = 9.8
atol(), atoll() and atof() functions in C/C++
In C/C++, atol(), atoll(), and atof() are functions used to convert strings to numbers of different types. These functions are Standard Library functions. In this article, we will learn these String-to-number conversion functions in C/C++.