Nearby lessons
25 of 124C - Input
Reading input in C with scanf(), getchar() and fgets(). Learn why scanf needs the & operator, how to read a full line with spaces, and how to clear the leftover newline from the buffer.
scanf() — Reading Values
scanf() takes a format string, just like printf, plus the address of each variable to fill:
Why the & is Required
C passes arguments by value — a function receives a copy. If scanf received a copy of age, it could only change the copy, and your variable would stay untouched.
The & operator hands over the variable's address instead, so scanf can write straight into the original storage.
printf only needs to read your variable, so it takes the value. scanf needs to change it, so it needs the address.scanf("%d", age) compiles with a warning and then crashes at runtime, because scanf treats whatever number was in age as a memory address.Reading Several Values at Once
One scanf can fill several variables. The user separates values with spaces, tabs or Enter:
The Problem with Strings and Spaces
scanf("%s", ...) stops at the first space, so it can never read a full name. Notice there is no & for a string — an array name is already an address:
fgets() — Reading a Whole Line
To capture spaces, use fgets(). It reads until Enter or until the buffer is full, whichever comes first — so it cannot overflow:
getchar() and the Leftover Newline
getchar() reads one character. The trap: after scanf("%d") the Enter key you pressed is still in the buffer, so the next character read is that \n, not your input.
Input Functions Compared
| Function | Reads | Spaces? | Safe? |
|---|---|---|---|
scanf("%d") | A number | Stops at space | Yes for numbers |
scanf("%s") | One word | No | No — can overflow |
fgets() | A full line | Yes | Yes |
getchar() | One character | Yes | Yes |
gets() | A full line | Yes | Never use it |
gets() was removed from the C standard in C11 because it has no way to know how big your array is. Any program using it can be crashed by long input. Always reach for fgets().- scanf("%d", &n) — the & is required for all types except strings.
- scanf stops at the first whitespace, so it cannot read "John Smith".
- Use fgets() to read a full line including spaces.
- A leftover \n in the buffer makes the next %c read garbage.
- Never use gets() — it cannot check the buffer size.