Learn C
#include "ioformatting/scanf.h"

Input with scanf in C

#concept

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.

#how it works
1

Pass addresses

scanf("%d", &age); — the & is mandatory (except arrays/strings, which decay); forgetting it writes through a garbage pointer.

2

Check the count

if (scanf("%d", &n) != 1) handles non-numeric input — the return value, not the variable, reports success.

3

Bound every %s

char buf[16]; scanf("%15s", buf); — the width (size − 1) is the only thing standing between %s and overflow.

4

Know its limits

Whitespace handling surprises, newlines linger, recovery is awkward — fgets + sscanf wins for robust interactive input.

#example
#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;
}
Output
Age? 30
In 5 years: 35
1The prompt prints without newline so input lands on the same line.
2Typing 30 assigns through &age; the == 1 check confirms one item parsed.
3The guarded branch computes and prints 35 — bad input would simply skip it.
#use cases
Quick numeric input in exercises and competitive programming
Checking parse success via the return count, never blind trust
Bounding %s with explicit widths against overflow
Graduating to fgets+sscanf for production-grade input

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.