How to Use the std::stod Family of Functions in C++
The std::stod
family of functions in C++ provides a powerful mechanism for converting strings to floating-point values. These functions are designed to interpret string contents as floating-point values, utilizing predefined parsing rules.
The suffix of each function indicates the type returned: std::stod
returns double
, std::stof
returns float
, and std::stold
returns long double
. They are included in the <string>
header file.
This article explores the usage of std::stod
, std::stof
, and std::stold
functions, which have been included in the C++ Standard Template Library (STL) since C++11.
Use std::stod
to Convert a string
Into a Floating Point Value in C++
The std::stod
function in C++ is used to convert a string to a double
value. The basic syntax is as follows:
double stod(const std::string& str, size_t* idx = 0);
-
str
: The string that you want to convert to adouble
. -
idx
(optional): A pointer to asize_t
variable that will store the position of the first unprocessed character in the string. If provided, the function sets the value pointed byidx
to the index of the first character after the converted part of the string.
Simple Conversion Example
The basic usage involves passing a string containing digits and a decimal delimiter to the std::stod
function. The function interprets the string as a valid floating-point number and stores it in a double
type.
Code:
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
int main() {
string str1 = "123.0";
string str2 = "0.123";
auto m1 = std::stod(str1);
auto m2 = std::stod(str2);
cout << "std::stod(\"" << str1 << "\") is " << m1 << endl;
cout << "std::stod(\"" << str2 << "\") is " << m2 << endl;
return EXIT_SUCCESS;
}
In this code, we initialize two string variables, str1
and str2
, with the values "123.0"
and "0.123"
, respectively. We then use the std::stod
function to convert these string representations of floating-point numbers into their corresponding double
values, storing the results in variables m1
and m2
.
Finally, we print the original strings along with the converted values using cout
.
Output:
std::stod("123.0") is 123
std::stod("0.123") is 0.123
The output demonstrates the successful conversion of string representations of floating-point numbers using the std::stod
function, showcasing its ability to interpret and convert numeric strings into their corresponding double-precision floating-point values.
Handling Non-Digit Characters
When the string contains non-digit characters, std::stod
handles two scenarios: starting with digits followed by other characters and starting with non-digit characters.
The function extracts digits before the first non-digit character (excluding the decimal delimiter) in the first case. In the second case, it throws a std::invalid_argument
exception.
Code:
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
int main() {
string str3 = "123.4 with chars";
auto m3 = std::stod(str3);
cout << "std::stod(\"" << str3 << "\") is " << m3 << endl;
return EXIT_SUCCESS;
}
In this code, we initialize a string variable, str3
, with the value "123.4 with chars"
. Utilizing the std::stod
function, we convert this string, which includes non-digit characters, into its corresponding double
value, storing the result in the variable m3
.
Subsequently, we print the original string along with the successfully converted double-precision floating-point value using cout
.
Output:
std::stod("123.4 with chars") is 123.4
The output demonstrates the effective conversion of the string "123.4 with chars"
to its numerical counterpart, emphasizing the ability of std::stod
to handle non-digit characters in the input string.
Leading Whitespace and Processed Characters
The functions discard leading whitespace characters, and an optional argument of type size_t*
can be used to store the number of processed characters. Whitespace characters are considered in the count even if they precede the valid floating-point number.
If we pass a string with multiple leading whitespace characters followed by the digits, the conversion will be performed successfully, as demonstrated in the following example.
Code:
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
int main() {
string str3 = "123.4 with chars";
string str5 = " 123.4";
size_t ptr1 = -1;
size_t ptr2 = -1;
auto m4 = std::stod(str3, &ptr1);
auto m5 = std::stod(str5, &ptr2);
cout << m4 << " - characters processed: " << ptr1 << endl;
cout << "std::stod(\"" << str5 << "\") is " << m5 << " - " << ptr2
<< " characters processed" << endl;
cout << "length: " << str5.size() << endl;
return EXIT_SUCCESS;
}
In this code, we explore the behavior of the std::stod
function in C++ for converting strings to double-precision floating-point values, specifically focusing on scenarios involving non-digit characters and leading whitespace. Two string variables, str3
and str5
, are initialized with values "123.4 with chars"
and " 123.4"
, respectively.
We use std::stod
to convert these strings to double values, tracking the number of processed characters using pointers ptr1
and ptr2
.
Output:
123.4 - characters processed: 5
std::stod(" 123.4") is 123.4 - 16 characters processed
length: 16
The output displays the converted values, the number of characters processed for each string, and the length of the second string. This demonstrates how std::stod
handles non-digit characters and leading whitespace during the conversion process, providing valuable insights into its functionality.
Conclusion
The std::stod
family in C++ efficiently converts strings to floating-point values, providing specialized functions for distinct numeric types. Demonstrated examples highlighted std::stod
’s successful conversion of strings like "123.0"
and "0.123"
, it’s handling of non-digit characters with exception handling, and its ability to manage leading whitespace characters.
These functions, integral to the C++ Standard Template Library since C++11, offer a robust and versatile solution for real-world data processing, particularly in scenarios involving user inputs or file data.
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook