C/C++ Arena

Step 1 of 6

std::format

C++20's std::format combines printf's compactness with type safety: {} placeholders are filled in order, and the format is checked at compile time when it's a literal.

std::format("{} has {} kills", name, k);        // "ropz has 25 kills"
std::format("{:>8}", "ab");                     // right-align in 8: "      ab"
std::format("{:<8}|", "ab");                    // left-align: "ab      |"
std::format("{:^7}", "mid");                    // center: "  mid  "
std::format("{:.2f}", 3.14159);                 // "3.14"
std::format("{:05}", 42);                       // zero-pad: "00042"
std::format("{:x} {:b}", 255, 5);               // hex and binary: "ff 101"

The spec after the colon is [fill][align][width][.precision][type].

Your turn: write std::string row(const std::string& name, int kills, double kd) producing the name left-aligned in 10 characters, kills right-aligned in 4, and the K/D right-aligned in 6 with 2 decimals. Use a single std::format call.

Next: Formatting your own types