Open In App

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++.

Methods to Convert String to Double

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



  1. Using stod() Function
  2. Using stold() Function
  3. Using atof() Function

Let’s discuss each of these methods in detail.

1. Using stod() Function

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

Return Value

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




// 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

2. Using stold() Function

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

Syntax

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

Parameters

Return Value

C++ Program to Convert String to Long Double Using stold() Function




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

Output
49.12

Complexity Analysis

3. Using atof() Function

In C++, the atof() method translates a string’s contents as a floating-point integer and returns its value as a double. It is declared inside <cstdlib> header file. 

Syntax

double atof (const char * str)

Parameters

Return Value

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




// C++ program to convert string
// to double using atof()
#include <iostream>
using namespace std;
 
// Driver code
int main()
{
    char s[] = "14.25";
    double num = atof(s);
    cout << num;
    return 0;
}

Output
14.25

Complexity Analysis

Related Articles


Article Tags :