Learn C
#include "ioformatting/fgets_lines.h"

Reading Lines Safely with fgets in C

#concept

fgets(buf, sizeof buf, stdin) reads a whole line with a hard size cap — the safe replacement for the removed-from-the-language gets(), which could never be used safely. It keeps the trailing newline when room allows (strip it: buf[strcspn(buf, "\n")] = 0), returns NULL at EOF, and never overflows the buffer.

The fgets-plus-sscanf pattern parses robustly: read the line, then sscanf(buf, "%d", &n) with its return checked. Input errors become ordinary string problems instead of stream-state puzzles.

#how it works
1

Size-capped reads

fgets(buf, sizeof buf, stdin) stops at size−1 characters, newline, or EOF — overflow is structurally impossible.

2

Strip the newline

buf[strcspn(buf, "\n")] = 0; deletes a trailing newline if present — strcspn finds it safely when absent too.

3

NULL means EOF/error

A NULL return with feof/ferror distinguishing end-of-file from read errors — check before using the buffer.

4

Parse with sscanf

sscanf(buf, "%d %d", &a, &b) parses from memory with a checkable return — retry logic without stream surgery.

#example
#include <stdio.h>
#include <string.h>
 
int main(void) {
char buf[64];
if (fgets(buf, sizeof buf, stdin) != NULL) {
buf[strcspn(buf, "\n")] = 0;
printf("got [%s]\n", buf);
}
return 0;
}
Output
got [Ada Lovelace]
1fgets reads the full line including spaces, capped at 63 characters plus terminator.
2strcspn locates the newline (or end) and overwrites it with a terminator.
3The brackets prove spaces survived and no newline leaked into the output.
#use cases
Reading names and sentences with spaces intact
Never touching gets() — removed from C11 for being unfixably unsafe
Robust numeric input via fgets + sscanf with return checks
Line-oriented config and data file parsing

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.