std::format in C++
C++20's answer to printf: type-checked templates with alignment, precision, and bases.
#include <format>
#include <iostream>
#include <string>
int main() {
std::string label = "latency";
double ms = 4.276;
std::cout << std::format("{:<10} {:>8.2f} ms\n", label, ms);
std::cout << std::format("{0} of {1} ({2:.1f}%)\n",
45, 60, 100.0 * 45 / 60);
std::cout << std::format("hex {0:#06x} binary {0:#b}\n", 42);
}
How it works
{:<10}left-aligns the label;{:>8.2f}right-aligns the number to two decimals.- Arguments can be addressed by index —
{0}and{1}reuse them in any order. {0:#06x}and{0:#b}print the same 42 in zero-padded hex and in binary.
Keywords and builtins used here
doubleintmain
The run, in numbers
- Lines
- 12
- Characters to type
- 323
- Tokens
- 97
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 83 seconds.
Step 3 of 3 in Strings & streams, step 21 of 27 in Language basics.