C++ Basics: Write Integers into a Bounded Buffer
Format integers without treating a bounded output range as a null-terminated string.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as to-chars-bounded-output-demo.cpp:
#include <array>
#include <charconv>
#include <iostream>
#include <string_view>
#include <system_error>
int main()
{
std::array<char, 8> buffer{};
const auto conversion = std::to_chars(buffer.data(), buffer.data() + buffer.size(), 2048);
if (conversion.ec != std::errc{}) {
return 1;
}
const std::string_view digits(buffer.data(),
static_cast<std::size_t>(conversion.ptr - buffer.data()));
std::cout << "Digits: " << digits << '\n';
std::cout << "Characters: " << digits.size() << '\n';
std::array<char, 2> small_buffer{};
const auto failed_conversion = std::to_chars(
small_buffer.data(), small_buffer.data() + small_buffer.size(), 2048);
std::cout << std::boolalpha << "Small buffer rejected: "
<< (failed_conversion.ec == std::errc::value_too_large) << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic to-chars-bounded-output-demo.cpp -o to-chars-bounded-output-demo &&
./to-chars-bounded-output-demoObserved output:
Digits: 2048
Characters: 4
Small buffer rejected: trueRead the result
The successful result points just after four digits. The view uses that length, so it does not depend on a terminator. The second buffer cannot hold the number and reports a size error.
Apply it carefully
to_chars does not append a null terminator. Check ec before reading the result: after a size failure, buffer contents are unspecified, not a usable truncated representation. A string_view borrows the buffer, so do not retain it after the array dies. Integer conversion needs no locale or heap allocation.
The C++ working draft describes the relevant rules. This example uses C++20 facilities; the current working draft also documents later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- to-chars-bounded-output-demo.cpp to-chars-bounded-output-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.