printf, scanf & fgets in C
From the C cheat sheet · Input & Output · verified Jul 2026
printf, scanf & fgets
Format specifiers and reading input.
c
// Quick Reference
printf("%d %.2f %s\n", 42, 3.14, "hi");
scanf("%d", &n);
fgets(buf, sizeof buf, stdin);💡 Match the specifier to the type: %d int, %f double, %s string, %zu size_t, %p pointer.
⚡ scanf writes into addresses, so pass &var - forgetting the & is a classic crash.
📌 Prefer fgets over scanf("%s") / gets for input - it is bounded and keeps spaces.
🟢 fgets leaves the trailing newline in the buffer; overwrite it with '\0' to trim.
ioprintfscanf