Lesson 71 +10 XP

Input with fgets and Buffer Safety

Input with fgets and Buffer Safety

scanf has a rule: it stops at whitespace, so reading a sentence needs a different tool: fgets.

Reading a sentence

#include <stdio.h>

int main() {
    char line[100];

    printf("Enter your sentence: ");
    fgets(line, sizeof(line), stdin);

    printf("You wrote: %s\n", line);
    return 0;
}

Why fgets is safer

fgets takes the buffer size and stops early instead of overflowing. It also keeps spaces.

The newline stays

fgets keeps the newline character from Enter. You may want to strip it.

TL;DR

  • fgets(buffer, size, stdin) reads a full line safely.
  • It won't overflow because you pass a maximum.
  • It keeps the newline character at the end.
  • Use it for sentences and multi-word input.