Mistake 20: relying on printf-style formatting makes type mismatches easy to introduce, while string streams make precise formatting awkward. std::format offers readable, fine-grained formatting with type-safe arguments. It can align output and enforce padding without manually converting values or managing a character buffer. section 4.3
Formatted student output
std::cout << std::format("{} is a student aged {} carrying a gpa of {:0^4}", dinah.name, dinah.age, dinah.gpa) << '\n'; The format specification produces a four-character, zero-padded GPA field: 4 becomes 4.00, 3.5 becomes 3.50, and 3.85 remains 3.85. section 4.3
Listing 4.7 Using std::format for fine-grained formatting functionality
struct Student {
std::string name;
int age;
double gpa;
Student(const std::string& n, int a, double g) : name(n), age(a), gpa(g) {}
};
int main() {
Student dinah("Dinah", 26, 3.3);
std::cout << std::format("{} is a student aged {} carrying a gpa of
{:0^4}", dinah.name, dinah.age, dinah.gpa) << '\n'; #1
return 0;
}
#1 sprintf-like functionality with type-safe behavior
Compare the concise std::format version with the supplied sprintf and stringstream implementations. section 4.3
