Convert String to Double

Convert String to Double in C++ (6 Programs)

BeginnerTopic: String Conversion Programs
Back

C++ Convert String to Double Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main() {
    string str = "123.456";
    
    // Method 1: Using stod()
    double num1 = stod(str);
    
    // Method 2: Using stringstream
    stringstream ss(str);
    double num2;
    ss >> num2;
    
    cout << "String: " << str << endl;
    cout << "Double (method 1): " << num1 << endl;
    cout << "Double (method 2): " << num2 << endl;
    
    return 0;
}
Output
String: 123.456
Double (method 1): 123.456
Double (method 2): 123.456

Understanding Convert String to Double

This program demonstrates 6 different methods to convert a string to a double: using stod(), stringstream, atof(), sscanf(), strtod(), and manual conversion.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents