C++ std::stod() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
std::stod

Definition

In C++, std::stod() converts a string to double.

Include <string>.

This is a free function from <string> that works with std::string (and sometimes wstring). Member functions like find live on the string object with a dot; helpers like this are called as std::stod(...).

Syntax

Pass the floating text.

C++
double d = std::stod("2.71828");
CallWhat it does
std::stod(str)Parse as double.

Most general-purpose floating parse in tutorials uses stod.

Library declarations
C++
double stod(const string& str, size_t* idx = 0);

Parameters

ParameterDescription
strInput.
idxOptional.

Return Value

Return ValueDescription
doubleParsed value.

C++ Examples

Example 1 — Basic stod()

Convert pi-like text.

C++
#include <iostream>
#include <string>

int main() {
    double d = std::stod("3.14159");
    std::cout << d << '\\n';
    return 0;
}

How It Works

  1. Digits and dot are parsed.
  2. Result is double.
  3. Printed value matches the text closely.

Example 2 — Negative double

Parse a signed float string.

C++
#include <iostream>
#include <string>

int main() {
    double d = std::stod("-0.5");
    std::cout << d << '\\n';
    return 0;
}

How It Works

  1. Leading minus is accepted.
  2. Value is -0.5.
  3. Type is double.

Example 3 — stod Throws

Handle bad text.

C++
#include <iostream>
#include <string>

int main() {
    try {
        std::stod("x");
    } catch (const std::invalid_argument&) {
        std::cout << "bad\\n";
    }
    return 0;
}

How It Works

  1. No numeric prefix.
  2. invalid_argument is thrown.
  3. Handler reports bad.

Frequently Asked Questions

String to double.
stof.
stold.
invalid_argument / out_of_range.
<string>.

Next: stof()

Keep going through the string functions. Convert a string to float.

stof() tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful