std::from_chars(3)
πΈ std::from_chars β std::from_chars πΈ
ok so this is the page for std::from_chars from the C++ Standard Library β yes bestie, the one that lives in <charconv> and does the parsing thing. Buckle up. π
β¨ Synopsis β¨
Defined in header <charconv>:
std::from_chars_result
from_chars( const char* first, const char* last, (1) (since C++17)
/* integer-type */& value, int base = 10 ); (constexpr since C++23)
std::from_chars_result
from_chars( const char* first, const char* last,
/* floating-point-type */& value, (2) (since C++17)
std::chars_format fmt = std::chars_format::general );
So what it does: it analyzes the character sequence [first, last) looking for a pattern described down below. If no characters match the pattern, or if the value you get from parsing the matched characters isn't representable in the type of value, then value stays unmodified. Otherwise the characters matching the pattern get interpreted as a text representation of an arithmetic value, and that gets stored in value. π
- Integer parsers: expects the same pattern that
std::strtoluses in the default ("C") locale with the given non-zero numeric base β with these exceptions, bestie:"0x"or"0X"prefixes are not recognized ifbaseis16- only the minus sign is recognized (not the plus sign), and only for signed integer types of
value - leading whitespace is not ignored
The library provides overloads for all cv-unqualified (since C++23) signed and unsigned integer types and char as the referenced type of the parameter value.
- Floating-point parsers: expects the same pattern that
std::strtoduses in the default ("C") locale β except:- the plus sign is not recognized outside of the exponent (only the minus sign is permitted at the beginning)
- if
fmthasstd::chars_format::scientificset but notstd::chars_format::fixed, the exponent part is required (otherwise it's optional) - if
fmthasstd::chars_format::fixedset but notstd::chars_format::scientific, the optional exponent is not permitted - if
fmtisstd::chars_format::hex, the prefix"0x"or"0X"is not permitted (the string"0x123"parses as the value"0"with unparsed remainder"x123") - leading whitespace is not ignored
In any case, the resulting value is one of at most two floating-point values closest to the value of the string matching the pattern, after rounding according to std::round_to_nearest.
The library provides overloads for all cv-unqualified standard (until C++23) floating-point types as the referenced type of the parameter value.
π¦ Parameters π¦
first,lastβ valid character range to parsevalueβ the out-parameter where the parsed value gets stored if it's a successbaseβ integer base to use: a value between2and36(inclusive)fmtβ floating-point formatting to use, a bitmask of typestd::chars_format
π Return value π
On success, returns a value of type std::from_chars_result such that ptr points at the first character not matching the pattern, or has the value equal to last if all characters match, and ec is value-initialized.
If there's no pattern match, returns a value of type std::from_chars_result such that ptr equals first and ec equals std::errc::invalid_argument. value is unmodified. π
If the pattern was matched but the parsed value is not in the range representable by the type of value, returns a value of type std::from_chars_result such that ec equals std::errc::result_out_of_range and ptr points at the first character not matching the pattern. value is unmodified.
π§ Exceptions π§
Throws nothing. literally nothing. icon behaviour. β¨
π Notes π
Unlike other parsing functions in C++ and C libraries, std::from_chars is locale-independent, non-allocating, and non-throwing. Only a small subset of parsing policies used by other libraries (such as std::sscanf) is provided. This is intended to allow the fastest possible implementation that's useful in common high-throughput contexts such as text-based interchange (JSON or XML). π
The guarantee that std::from_chars can recover every floating-point value formatted by std::to_chars exactly is only provided if both functions are from the same implementation. no cap.
A pattern consisting of a sign with no digits following it is treated as a pattern that did not match anything.
Feature-test macros, bestie:
__cpp_lib_to_charsβ201611L(C++17) β Elementary string conversions (std::from_chars,std::to_chars)__cpp_lib_to_charsβ202306L(C++26) β Testing for success or failure of<charconv>functions__cpp_lib_constexpr_charconvβ202207L(C++23) β Add constexpr modifiers tostd::from_charsandstd::to_charsoverloads for integral types
π Example π
// Run this code
#include <cassert>
#include <charconv>
#include <iomanip>
#include <iostream>
#include <optional>
#include <string_view>
#include <system_error>
int main()
{
for (std::string_view const str : {"1234", "15 foo", "bar", " 42", "5000000000"})
{
std::cout << "String: " << std::quoted(str) << ". ";
int result{};
auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), result);
if (ec == std::errc())
std::cout << "Result: " << result << ", ptr -> " << std::quoted(ptr) << '\n';
else if (ec == std::errc::invalid_argument)
std::cout << "This is not a number.\n";
else if (ec == std::errc::result_out_of_range)
std::cout << "This number is larger than an int.\n";
}
// C++23's constexpr from_char demo / C++26's operator bool() demo:
auto to_int = [](std::string_view s) -> std::optional<int>
{
int value{};
#if __cpp_lib_to_chars >= 202306L
if (std::from_chars(s.data(), s.data() + s.size(), value))
#else
if (std::from_chars(s.data(), s.data() + s.size(), value).ec == std::errc{})
#endif
return value;
else
return std::nullopt;
};
assert(to_int("42") == 42);
assert(to_int("foo") == std::nullopt);
#if __cpp_lib_constexpr_charconv and __cpp_lib_optional >= 202106
static_assert(to_int("42") == 42);
static_assert(to_int("foo") == std::nullopt);
#endif
}
β Output β
String: "1234". Result: 1234, ptr -> ""
String: "15 foo". Result: 15, ptr -> " foo"
String: "bar". This is not a number.
String: " 42". This is not a number.
String: "5000000000". This number is larger than an int.
π Defect reports π
The following behavior-changing defect reports were applied retroactively to previously published C++ standards:
- LWG 2955 β applied to C++17 β as published: this function was in
<utility>and usedstd::error_codeβ corrected: moved to<charconv>and usesstd::errc - LWG 3373 β applied to C++17 β as published:
std::from_chars_resultmight have additional members β corrected: additional members are prohibited
π See also π
from_chars_result(C++17) β the return type ofstd::from_chars(class)to_chars(C++17) β converts an integer or floating-point value to a character sequence (function)stoi,stol,stoll(C++11) β converts a string to a signed integer (function)stof,stod,stold(C++11) β converts a string to a floating point value (function)strtol,strtoll(C++11) β converts a byte string to an integer value (function)strtof,strtod,strtoldβ converts a byte string to a floating-point value (function)scanf,fscanf,sscanfβ reads formatted input fromstdin, a file stream or a buffer (function); extracts formatted dataoperator>>β public member function ofstd::basic_istream<CharT,Traits>
ok that's the whole page, you ate that π go parse something iconic bestie π«Ά
source: cppreference.com β version 2024.06.10 β page: std::from_chars(3) β¨ππ¦
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms