C++ Program For String to Double Conversion
In this article, we will learn how to convert strings to double in C++. For this conversion, there are 3 ways as follows:
- Using stod().
- Using stold().
- Using atof().
Let’s start discussing each of these methods in detail.
Example:
Input: s1 = “14.25”
s2 = “34.87”Output: s1 + s2
long: 49.12
1. Using stod()
In C++, the stod() function performs a string to double conversion.
Syntax:
double stod(const std::string& str, std::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.
Below is the C++ program to convert string to double using stod():
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
Time complexity: O(1).
Auxiliary Space: O(1).
2. Using stold()
In C++, the stold() function performs a string to long double conversion.
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.
Below is the C++ program to convert string to long double using stold():
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
Time complexity: O(1).
Auxiliary Space: O(1).
3. Using atof()
In C++, the atof() method translates a string’s contents as a floating-point integer and returns its value as a double.
Syntax:
double atof (const char * str)
Parameters: The function accepts single mandatory parameter str which is the representation of a floating-point number.
Below is the C++ program to convert string to double using atof():
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
Time complexity: O(1).
Auxiliary Space: O(1).
Please Login to comment...