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
