printf formats values into output using a format string with placeholders. If a placeholder’s type or count does not match the supplied arguments, the code can compile yet produce undefined behavior, incorrect output, or a crash. section 4.3 section 6.1
When maintaining C++ code, weigh compatibility against safer and clearer formatting:
- Keep printf-family formatting when legacy constraints require it, but check each format specifier and its corresponding argument. section 6.1
- Consider std::format for type-safe formatting; string streams can work but may become awkward for fine-grained output. section 4.3
Listing 4.5 Using sprintf 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);
char buffer[256];
sprintf(buffer, "%s is a student aged %d carrying a gpa of %.2f",
dinah.name.c_str(), dinah.age, dinah.gpa); #1
std::cout << buffer << '\n';
return 0;
}
This Student example uses sprintf with a name, age, and GPA; the format placeholders must match the argument types and order. 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
The same Student output uses std::format as a type-safe alternative to sprintf-style formatting. section 4.3
