format/formatchars.cpp

The following code example is taken from the book
C++23 - The Complete Guide by Nicolai M. Josuttis, Leanpub, 2026
The code is licensed under a Creative Commons Attribution 4.0 International License. Creative Commons License

// raw code

#include <string>
#include <print>

int main()
{
  std::string s = "backslash: '\\'";    // some chars with single quote and newline
  std::println("default:     {}", s);
  std::println("{{:s}} :       {:s}", s);
  std::println("{{:?}} :       {:?}", s);
  std::println("{{:.4}} :      {:.4}", s);
  std::println("{{:.4?}} :     {:.4?}", s);
  std::println("{{:*^20?}} :   {:*^20?}", s);
  std::println("{{:*^20.4?}} : {:*^20.4?}\n", s);

  std::println("s[11] (single quote):");
  std::println("  {{}} :       {}", s[11]);
  std::println("  {{:?}} :     {:?}\n", s[11]);

  std::println("s[12] (newline):");
  std::println("  {{}} :       {}", s[12]);
  std::println("  {{:?}} :     {:?}", s[12]);
}