liveBook · Manning

Printf

As explained in 100 C++ Mistakes and How to Avoid Them

printf is a C standard-library function that formats values and writes the resulting text to an output stream.

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

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains type and argument-count mismatches, their runtime risks, and alternatives without detailing implementation internals.
Examples
Uses Student name, age, and GPA output to contrast sprintf with std::format.
What you can do after
Evaluate format-string risks and compare printf-family output with C++ formatting alternatives.
How it connects
Connects printf to format specifiers, scanf, string streams, and std::format.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.