C in 100 Seconds: fgets | Episode 13
Video: C in 100 Seconds: Safe Input with fgets | Episode 13 by Taught by Celeste AI - AI Coding Coach
Watch full page →fgets — Safe String Input in C
C in 100 Seconds, Episode 13
scanf stops at whitespace and has no buffer protection. fgets solves both problems — it reads a full line and respects a size limit.
Reading a Line
char line[20];
fgets(line, sizeof(line), stdin);
Three arguments:
1. Buffer — where to store the input
2. Size — maximum characters to read (including the null terminator)
3. Stream — stdin for keyboard input
If the user types more than 19 characters, fgets stops at 19 and adds a \0. No overflow.
The Newline Problem
fgets includes the newline character when the user hits Enter. You usually want to strip it:
line[strcspn(line, "\n")] = 0;
strcspn finds the position of the first \n in the string. Setting that character to 0 (the null terminator) effectively removes the newline.
Seeing the Result
printf("You said: [%s]\n", line);
printf("Length: %lu\n", strlen(line));
The brackets make it easy to see exactly what was captured, including any trailing spaces.
Why fgets Over scanf?
- Buffer safety — you specify a maximum size
- Full lines — spaces are included in the input
- Predictable — no leftover characters in the input buffer
For any real application that reads text from users, fgets is the standard approach.
Full Code
#include <stdio.h>
#include <string.h>
int main() {
char line[20];
printf("Enter a sentence: ");
fgets(line, sizeof(line), stdin);
line[strcspn(line, "\n")] = 0;
printf("You said: [%s]\n", line);
printf("Length: %lu\n", strlen(line));
return 0;
}
Compile and Run
gcc fgets.c -o fgets
./fgets
Next episode: Constants and Macros — values that never change.
Student code: github.com/GoCelesteAI/c-in-100-seconds/episode13