Step 1 of 7
std::format
You've formatted output two ways so far: C's printf (compact, but not type-safe: a wrong %d is undefined behavior) and streams with <iomanip> (type-safe, but wordy and full of sticky state). C++20's std::format (from <format>) combines the best of both: {} placeholders filled in order, compact width and precision specs, and the format string is checked at compile time when it's a literal.
#include <format>
#include <iostream>
#include <string>
int main() {
std::string item = "coffee";
int qty = 3;
double price = 2.5;
std::cout << std::format("{} x {} = {:.2f}\n", qty, item, qty * price);
std::cout << std::format("[{:<8}][{:>8}][{:^8}]\n", "left", "right", "mid");
std::cout << std::format("[{:*^10}]\n", "hi"); // fill with *
std::cout << std::format("{:03} {:x} {:X} {:b}\n", 7, 255, 255, 5);
std::cout << std::format("{1} before {0}\n", "second", "first"); // explicit positions
std::string line = std::format("{:>6.1f}%", 42.25); // it's just a string
std::cout << line << " (" << line.size() << " chars)\n";
}
3 x coffee = 7.50
[left ][ right][ mid ]
[****hi****]
007 ff FF 101
first before second
42.2% (7 chars)
The spec after the colon
{:[fill][align][width][.precision][type]}, each part optional:
| Part | Examples |
|---|---|
| align | < left, > right, ^ center |
| fill | any character before the align, like * in {:*^10} |
| width | minimum characters: {:8} |
.precision |
digits after the point for floats: {:.2f} |
| type | f fixed, x/X hex, b binary, e scientific |
0 before width |
zero-pad numbers: {:03} |
Numbers are right-aligned by default and strings left-aligned. Unlike setw, nothing is sticky: each placeholder has its own spec. And 42.25 became 42.2 because it's exactly halfway, and ties round to the even digit.
Your task
One call with three placeholders: {:<10} for the name, {:>4} for the kills and {:>6.2f} for the K/D.
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.