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:
- Using stod() Function
- Using stold() Function
- 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
- 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; } |
49.12
Complexity Analysis
- Time complexity: O(1)
- Auxiliary Space: O(1)
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
- str: the string to convert.
- pos: address of integer to store the index of the first unconverted character. This parameter can also be a null pointer, in which case it is not used.
Return Value
- Converted long double value.
C++ Program to Convert String to Long Double Using stold() Function
C++
// 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; } |
49.12
Complexity Analysis
- Time complexity: O(1)
- Auxiliary Space: O(1)
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
- The function accepts a single mandatory parameter str which is the string representation of a floating-point number.
Return Value
- Converted long double value.
C++ Program to Convert String to Double Using atof() Function
C++
// 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; } |
14.25
Complexity Analysis
- Time complexity: O(1)
- Auxiliary Space: O(1)