CKTIS / C++
std::stod — convert text to double
std::stod from <string> converts a numeric prefix of text to double. The optional idx parameter identifies where conversion stopped; remaining characters do not automatically cause an error.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <string>
// Overload synopsis (declared by <string>):
// namespace std {
// double stod(const std::string& str, std::size_t* idx = nullptr);
// double stod(const std::wstring& str, std::size_t* idx = nullptr);
// }std::stod from <string> accepts a std::string or std::wstring and returns double. The overloads use strtod and wcstod, respectively.
The optional idx points to a std::size_t. On success, it receives the index of the first unconverted character. The default nullptr disables storing that index. Prefix conversion is allowed: "42kg" produces 42, leaving "kg". To require consumption of the entire text, check pos == text.size(); trailing whitespace also remains unconverted.
No conversion causes std::invalid_argument. std::stod throws std::out_of_range if strtod or wcstod sets errno to ERANGE, or if the converted value is outside the representable range of double. On underflow, the underlying function may return a representable value without setting errno to ERANGE. In that case, C++23 does not require std::stod to throw std::out_of_range. Do not rely on the value of idx after an exception.
The example demonstrates successful prefix conversion and detection of the remaining suffix. Running the displayed code unchanged produced standard output that exactly matched the output shown.
Examples
#include <cstddef>
#include <iostream>
#include <stdexcept>
#include <string>
int main() {
const std::string text = "42kg";
std::size_t pos = 0;
try {
const double value = std::stod(text, &pos);
std::cout << "value=" << value << '\n';
std::cout << "pos=" << pos << '\n';
std::cout << "rest=" << text.substr(pos) << '\n';
std::cout << "complete=" << (pos == text.size()) << '\n';
} catch (const std::invalid_argument&) {
std::cout << "invalid_argument\n";
return 1;
} catch (const std::out_of_range&) {
std::cout << "out_of_range\n";
return 1;
}
}
Result
value=42 pos=2 rest=kg complete=0
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.