Convert String to Double

Convert String to Double in C++

C++Beginner
C++
#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

Convert String to Double in C++

This program teaches you how to convert a string containing a decimal number into a double (floating-point number) in C++. This conversion is essential when reading decimal numbers from user input, files, or external data sources. Understanding different conversion methods helps you handle decimal numbers accurately and safely in your programs.

What This Program Does

The program converts a string like "123.456" into a double value 123.456. This conversion is necessary because:

  • User input from cin is often read as strings
  • File data containing decimal numbers comes as strings
  • Network data and APIs return numbers as strings
  • You need double precision for accurate decimal calculations

Example:

  • Input string: "123.456"
  • Output double: 123.456

Methods for Conversion

Method 1: Using stod() (String to Double)

cpp
double num1 = stod(str);
  • Most modern and recommended method in C++
  • Part of the <string> header (C++11 and later)
  • Automatically handles the conversion
  • Throws exceptions for invalid input
  • Handles scientific notation (e.g., "1.23e2" = 123.0)

Method 2: Using stringstream

cpp
stringstream ss(str);
double num2;
ss >> num2;
  • Very flexible - can convert multiple values
  • Similar syntax to cin, making it familiar
  • Can handle multiple types in one stream

Error Handling

Different methods handle errors differently:

  • stod(): Throws std::invalid_argument or std::out_of_range exceptions

  • stringstream: Sets failbit on error

  • Best Practice: Use stod() with try-catch for robust error handling

Summary

  • Converting strings to doubles is essential for processing decimal numbers from input.
  • stod() is the recommended modern C++ method - simple and safe.
  • stringstream is flexible and great for multiple conversions.
  • Always handle errors appropriately, especially with user input.

This program is crucial for beginners learning how to work with different data types and process user input in C++ programs.