Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::to_chars — write a number into a character buffer

std::to_chars writes a number's textual representation into a caller-provided buffer. Its result contains an end pointer and an error code; the function does not append a terminating '\0'.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <charconv>
std::to_chars(first, last, value);
std::to_chars(first, last, integer_value, base);
std::to_chars(first, last, floating_value, fmt);
std::to_chars(first, last, floating_value, fmt, precision);

std::to_chars, declared in <charconv>, writes a number into a valid, writable range [first, last). It does not append '\0' and throws no exceptions. Treat the resulting data as a character range, not automatically as a null-terminated string.

The returned std::to_chars_result contains std::to_chars_result::ptr of type char* and std::to_chars_result::ec of type std::errc. When ec == std::errc{}, conversion succeeded: ptr points just past the last character written, and ptr - first gives the length. If the buffer is too small, ec == std::errc::value_too_large, ptr == last, and the range's contents are unspecified. Do not use that buffer as a partial result.

For integers, base defaults to 10 and must be within 2–36. Digits above 9 use a–z; negative values receive -. The bool overload is deleted. Floating-point overloads optionally accept std::chars_format and a precision; they use "C" locale formatting rules regardless of current locale settings.

The example checks ec before using ptr and constructs a std::string_view with an explicit length. It targets compilation with -std=c++23; it does not attest production-runtime behavior. The eel.is sources show an evolving working draft, so they may contain additions later than C++23.

Examples

#include <charconv>
#include <cstddef>
#include <iostream>
#include <string_view>
#include <system_error>

int main() {
    char buffer[16];
    const std::to_chars_result result =
        std::to_chars(buffer, buffer + sizeof buffer, 255, 16);

    if (result.ec != std::errc{}) {
        std::cerr << "conversion failed\n";
        return 1;
    }

    const std::string_view text(
        buffer, static_cast<std::size_t>(result.ptr - buffer));
    std::cout << text << '\n';
}

Result

ff

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources