Lesson 18 / 36

Reading String Input

scanf's hidden traps, and why fgets is safer.

scanf("%s", ...) has no limit

scanf("%s", buf) reads until whitespace with no bounds checking — a long input overflows buf. It also stops at the first space, so it can't read full sentences.

fgets reads a whole line, safely

fgets takes a size limit and reads up to a newline, including spaces.

char line[50];
printf("Enter your name: ");
fgets(line, sizeof(line), stdin);

// fgets keeps the trailing '\n' -- strip it:
line[strcspn(line, "\n")] = '\0';
printf("Hi, %s!\n", line);

Mixing scanf and fgets

scanf("%d", &n) leaves the trailing \n in the input buffer, which a following fgets will immediately read as an empty line. Consume it first, e.g. with getchar().