Input with scanf in C
scanf parses standard input according to a format string, storing through pointers — scanf("%d", &age) needs age's address because C passes arguments by value. It returns the count of successfully assigned items, which is the correct loop/test condition (EOF on end-of-file).
scanf is fragile for real input: %s without a width overflows buffers (always write %15s for char[16]), trailing newlines linger, and type mismatches corrupt memory. Learn it for fluency and quick tools, then prefer fgets-plus-sscanf for anything user-facing.
Pass addresses
scanf("%d", &age); — the & is mandatory (except arrays/strings, which decay); forgetting it writes through a garbage pointer.
Check the count
if (scanf("%d", &n) != 1) handles non-numeric input — the return value, not the variable, reports success.
Bound every %s
char buf[16]; scanf("%15s", buf); — the width (size − 1) is the only thing standing between %s and overflow.
Know its limits
Whitespace handling surprises, newlines linger, recovery is awkward — fgets + sscanf wins for robust interactive input.
#include <stdio.h> int main(void) { int age = 0; printf("Age? "); if (scanf("%d", &age) == 1) { printf("In 5 years: %d\n", age + 5); } return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.