how to convert a string to a double c++
To convert a string to a double in C++, you can use the std::stod()
function. Here are the steps to do it:
- Include the necessary header file:
#include <string>
- Create a string variable containing the string you want to convert:
std::string str = "3.14";
- Use the
std::stod()
function to convert the string to a double:
double value = std::stod(str);
- The variable
value
will now hold the converted double value.
Here's the complete code example:
#include <iostream>
#include <string>
int main() {
std::string str = "3.14";
double value = std::stod(str);
std::cout << "Converted value: " << value << std::endl;
return 0;
}
This code will output:
Converted value: 3.14
And that's how you can convert a string to a double in C++ using the std::stod()
function.