A string can be converted to a floating-point value when numerical calculations are required on textual data. C++ provides functions such as stod(), stold(), and atof() for converting numeric strings into floating-point values.
- stod() converts a string to double.
- stold() converts a string to long double, while atof() converts a C-style string to double.
Examples:
Input: "14.25"
Output: 14.25Input: "34.87"
Output: 34.87
Methods to Convert String to Double in C++
The conversion can be performed using the following methods:
1. Using stod()
The stod() function converts a std::string containing a valid floating-point number into a double.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "14.25";
// Convert string to double
double num = stod(str);
cout << num;
return 0;
}
Output
14.25
Example: For the input string "14.25":
- stod() reads the numeric characters from the string.
- It converts the value to double.
- The converted value is stored in num.
2. Using stold()
The stold() function converts a std::string into a long double. It is useful when higher floating-point precision is required.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "34.87";
// Convert string to long double
long double num = stold(str);
cout << num;
return 0;
}
Output
34.87
Example: For the input string "34.87":
- stold() converts the string into a long double.
- The converted value is stored in num.
- The value can then be used in floating-point calculations.
3. Using atof()
The atof() function converts a C-style string (const char*) containing a floating-point number into a double. It is declared in the <cstdlib> header.
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
const char* str = "14.25";
// Convert C-style string to double
double num = atof(str);
cout << num;
return 0;
}
Output
14.25
Example: For the input "14.25":
- atof() takes a C-style string.
- It converts the numeric text into a double.
- The converted value is stored in num.