CKTIS / C++
std::from_chars: allocation-free conversion from characters
std::from_chars parses a number in [first, last), returning the match end and an error code without exceptions.
Version: C++23
Syntax
struct std::from_chars_result {
const char* ptr;
std::errc ec;
};
constexpr std::from_chars_result std::from_chars(
const char* first, const char* last, /* integer type */& value, int base = 10);
std::from_chars_result std::from_chars(
const char* first, const char* last, /* floating type */& value,
std::chars_format fmt = std::chars_format::general);std::from_chars(first, last, value, base) from <charconv> parses an integer from an explicitly bounded character range; a separate overload handles floating-point values and std::chars_format. The returned std::from_chars_result contains std::from_chars_result::ptr, which points to the first unmatched character, and the error code std::from_chars_result::ec. It allocates nothing, is locale-independent, and needs no null terminator.
The example reads the beginning of "2a rest" in base 16. It sets value to 42, leaves ptr after two characters, and produces a clear std::errc, so it prints 42 2 1. Parsing does not skip leading whitespace. The integer form accepts no leading +, accepts - only for a signed destination, and does not treat 0x as a prefix even for base 16.
If no character matches, the result is ptr == first and errc::invalid_argument, with value unchanged. A value outside the destination range yields errc::result_out_of_range and also leaves value unchanged, while ptr still marks the end of the matched sequence. Integer base must be 2..36. Floating parsing follows chars_format rules (for example, an exponent is required for scientific and forbidden for fixed) and likewise recognizes no 0x prefix in hex mode.
Examples
#include <charconv>
#include <iostream>
#include <string_view>
#include <system_error>
int main() {
const std::string_view text = "2a rest";
int value = -1;
const auto result = std::from_chars(text.data(), text.data() + text.size(), value, 16);
std::cout << value << ' ' << (result.ptr - text.data()) << ' '
<< (result.ec == std::errc{}) << '\n';
}
Result
42 2 1
std::from_chars → 42 2 1