format/println.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 <print>
#include <string>

int main()
{
  std::string str{"hello"};
  std::println("String '{}' has {} characters", str, str.size());
  std::println("{1} is the size of string '{0}'\n", str, str.size());

  std::println("val: {:7}",    42);       // minimum width
  std::println("val: {:7.2f}", 42.0);     // two digits after dot
  std::println("val: {:7}",    true);     // Boolean value
  std::println("val: {:7b}",   1000);     // binary
  std::println("{0}: {0:+07d}\n", '?');   // character with its value

  std::println("val: {:<7}",   42);       // left aligned
  std::println("val: {:^7}",   42);       // centered
  std::println("val: {:*^7}",  42);       // centered with fill character
}