C · 1 · Foundations6 / 35 · 17%
Formatted I/O Done Right
printf/scanf format specifiers, and why scanf("%s") is a security hole.
Examples: printf, snprintf, fgets, %d %s %zu
shortcuts: ← prev · → next · M mark
1
printf Specifiers
Match the specifier to the type exactly — mismatches are undefined behavior.
Example
example
printf("%d\n", 42); // int
printf("%u\n", 42u); // unsigned
printf("%ld\n", 42L); // long
printf("%zu\n", sizeof(int)); // size_t
printf("%.3f\n", 3.14159); // 3.142
printf("%p\n", (void*)&x); // pointer
printf("%-10s|\n", "left"); // width + left alignOutput
42 42 42 4 3.142 0x7ffd… left |
2
Reading Input Safely
Never use gets(). Prefer fgets + explicit parsing.
Example
example
char line[128];
if (fgets(line, sizeof line, stdin)) {
line[strcspn(line, "\n")] = '\0'; // trim newline
int n = atoi(line);
}WATCH OUT
scanf("%s", buf) has no length limit — it will overflow buf. Use "%127s" or fgets.
3
snprintf for Building Strings
Always bounded, always NUL-terminated, returns the length it wanted.
Example
example
char buf[32];
int need = snprintf(buf, sizeof buf, "user-%d", id);
if (need >= (int)sizeof buf) {
// output was truncated
}4
Quick Check
Test yourself on specifier mismatches.
Quick check
What is the correct specifier for a size_t value?