std::to_chars

Header: <charconv>

Converts value into a character string by successively filling the range [first,last), where [first,last) is required to be a valid range.

# Declarations

std::to_chars_result
to_chars( char* first, char* last,
/* integer-type */ value, int base = 10 );

(since C++17) (constexpr since C++23)

std::to_chars_result
to_chars( char*, char*, bool, int = 10 ) = delete;

(since C++17)

std::to_chars_result
to_chars( char* first, char* last, /* floating-point-type */ value );

(since C++17)

std::to_chars_result
to_chars( char* first, char* last, /* floating-point-type */ value,
std::chars_format fmt );

(since C++17)

std::to_chars_result
to_chars( char* first, char* last, /* floating-point-type */ value,
std::chars_format fmt, int precision );

(since C++17)

# Parameters

# Return value

On success, returns a value of type std::to_chars_result such that ec equals value-initialized std::errc and ptr is the one-past-the-end pointer of the characters written. Note that the string is not NUL-terminated.

# Notes

Unlike other formatting functions in C++ and C libraries, std::to_chars is locale-independent, non-allocating, and non-throwing. Only a small subset of formatting policies used by other libraries (such as std::sprintf) is provided. This is intended to allow the fastest possible implementation that is 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.

It is required to explicitly cast a bool value to another integer type if it is wanted to format the value as “0”/“1”.

# Example

#include <charconv>
#include <iomanip>
#include <iostream>
#include <string_view>
#include <system_error>
 
void show_to_chars(auto... format_args)
{
    const size_t buf_size = 10;
    char buf[buf_size]{};
    std::to_chars_result result = std::to_chars(buf, buf + buf_size, format_args...);
 
    if (result.ec != std::errc())
        std::cout << std::make_error_code(result.ec).message() << '\n';
    else
    {
        std::string_view str(buf, result.ptr - buf);
        std::cout << std::quoted(str) << '\n';
    }
}
 
int main()
{
    show_to_chars(42);
    show_to_chars(+3.14159F);
    show_to_chars(-3.14159, std::chars_format::fixed);
    show_to_chars(-3.14159, std::chars_format::scientific, 3);
    show_to_chars(3.1415926535, std::chars_format::fixed, 10);
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 2955C++17this function was in and used std::error_codemoved to and uses std::errc
LWG 3266C++17bool argument was accepted and promoted to intrejected by a deleted overload
LWG 3373C++17std::to_chars_result might have additional membersadditional members are disallowed

# See also