C++ cstdlib atof() Function
Example
Read the decimal number from the text "4.25 kg", and multiply it by 2:
char text[] = "4.25 kg";
double weight = atof(text);
cout << weight * 2;
Definition and Usage
The atof() function reads a decimal number at the start of a C-style string (text stored in a char array), and returns it as a double.
It skips spaces at the start, and stops at the first character that is not part of the number. If the text does not start with a number, it returns 0.
The atof function is defined in the <cstdlib> header file.
Tip: To use atof() with a string, write atof(myText.c_str()). You can also use stod(), see Convert Strings and Numbers.
Syntax
double atof(const char* str);
Parameter Values
| Parameter | Description |
|---|---|
| str | Required. The C-style string to read the number from. |
Technical Details
| Returns: | A double with the number. If no number is found, it returns 0. |
|---|