This is an old thread, but as fmt might make it into the standard, here is an additional solution:
#include <fmt/format.h>
int n = 999;
const auto str = fmt::format("{:0>{}}", n, 6);
Note that the fmt::format("{:0>6}", n)
works equally well when the desired width is known at compile time. Another option is abseil:
#include <absl/strings/str_format.h>
int n = 999;
const auto str = absl::StrFormat("%0*d", 6, n);
Again, abs::StrFormat("%06d", n)
is possible. boost format is another tool for this problem:
#include <boost/format.hpp>
int n = 999;
const auto str = boost::str(boost::format("%06d") % n);
Unfortunately, variable width specifier as arguments chained with the %
operator are unsupported, this requires a format string setup (e.g. const std::string fmt = "%0" + std::to_string(6) + "d";
).
In terms of performance, abseil and fmt claim to be very attractive and faster than boost. In any case, all three solutions should be more efficient than std::stringstream
approaches, and other than the std::*printf
family, they do not sacrifice type safety.