The dark ages of C++20 string formatting

Tags

  • cpp

Abhorrent.

char strbuf[10+1];
int meaning = 42;
std::sprintf(strbuf, "%010d", meaning);
std::string message(strbuf);

Soon 21st century will catch up.

std::string message = std::format("The answer is {:010d}.", 42);

In the meantime, Abseil.

#include "absl/strings/str_format.h"
std::string message = absl::StrFormat("The answer is %010d.", 42);

And don’t forget to include str_format in your BUILD Bazel file.

cc_binary(
  name="hello_world",
  deps=["@com_google_absl//absl/strings:str_format",],
  srcs=["hello_world.cc"]
)