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 according to a format string and writes the resulting text. Each conversion specifier must match its argument: a mismatch can produce undefined behavior, incorrect data, a crash, or worse. section 6.1

Treat these as practical maintenance hazards:

  • Format strings are compact but difficult to read. Specifiers such as %lf, %i, %d, and %s require separate knowledge rather than revealing the destination type directly. section 6.1
  • Verify every argument against its conversion. Passing an integer where %s expects text can cause undefined behavior instead of merely producing an imperfect message. section 6.1
  • Prefer typed stream operations when compatibility permits; the types make conversions easier to read and failures can be checked incrementally. section 6.1
Listing 6.1 Using complicated format specifiers to determine conversions
int main() {
    const char* str = "3.14159 042 boxes .3";
    double pi;
    int cats;
    int mice;
    char buffer[5];
 
    int count = sscanf(str, "%lf%*c%i%s%d", &pi, &cats, 
        buffer, &mice);                                       #1
    if (count != 4)                                           #2
        std::cout << "error reading value " << count+1 << '\n';
 
    printf("%f being eaten by %d cats in %s along with %d mice\n",
        pi, cats, mice, mice);                                #3
    return 0;
}

Inspect the production-style example where a complicated scanf format is followed by a mismatched printf call. section 6.1

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

How deep it goes
Explains format matching and undefined behavior, then contrasts printf with typed streams.
Examples
Uses a mismatched printf call, complicated sscanf conversions, and an istringstream-based correction.
What you can do after
Diagnose format mismatches and replace fragile output code incrementally with checked, type-directed operations.
How it connects
Connects printf with scanf, format specifiers, type conversion, and C++ streams.

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.