How to use stod() Function In C++

In C++, the stod() function performs a string to double conversion. It is a library function defined inside <string.h> header file.

Syntax

double stod(const string& str, size_t* pos = 0);

Parameters

  • str: the string to convert.
  • pos: address of an integer to store the number of characters processed. This parameter can also be a null pointer, in which case it is not used.

Return Value

  • Converted double value.

C++ Program to Convert String to Double Using stod() Function

C++




// C++ program to convert string
// to double using stod()
#include <iostream>
using namespace std;
 
// Driver code
int main()
{
    char s1[] = "14.25";
    char s2[] = "34.87";
    double n1 = stod(s1);
    double n2 = stod(s2);
    double res = n1 + n2;
    cout << res;
    return 0;
}


Output

49.12

Complexity Analysis

  • Time complexity: O(1)
  • Auxiliary Space: O(1)

C++ Program For String to Double Conversion

There are situations, where we need to convert textual data into numerical values for various calculations. In this article, we will learn how to convert strings to double in C++.

Similar Reads

Methods to Convert String to Double

We can convert String to Double in C++ using the following methods:...

1. Using stod() Function

In C++, the stod() function performs a string to double conversion. It is a library function defined inside header file....

2. Using stold() Function

...

3. Using atof() Function

In C++, the stold() function performs a string to long double conversion. Like stod() function, this function is also defined inside header file....