Reading Lines Safely with fgets in C
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.
Size-capped reads
fgets(buf, sizeof buf, stdin) stops at size−1 characters, newline, or EOF — overflow is structurally impossible.
Strip the newline
buf[strcspn(buf, "\n")] = 0; deletes a trailing newline if present — strcspn finds it safely when absent too.
NULL means EOF/error
A NULL return with feof/ferror distinguishing end-of-file from read errors — check before using the buffer.
Parse with sscanf
sscanf(buf, "%d %d", &a, &b) parses from memory with a checkable return — retry logic without stream surgery.
#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;}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.