Syntax
auto result = std::to_chars(first, last, number);Examples
C++ std::to_chars formatting
Save as main.cpp and compile with a C++20 compiler, for example g++ -std=c++20 main.cpp -o example. The article states the minimum language version.
#include <charconv>
#include <system_error>
#include <iostream>
int main() {
char buffer[32];
auto result = std::to_chars(buffer, buffer + sizeof buffer, 255, 16);
if (result.ec == std::errc{}) {
std::cout.write(buffer, result.ptr - buffer);
std::cout << '\n';
}
}- Output: ff. Base 16 formats an integer; result.ptr points just after the written bytes.
Best practices
- Check ec before reading the buffer. to_chars does not append a null terminator; use the returned end pointer.
Runtime & versions
Compiled native applications. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ISO C++ resources