Learn C Programming

Lesson 3 of 9 · Strings

Module 10 · Strings

Reading Strings Safely: fgets, and Why gets Was Removed

Free with an accountReading

Maria prints labels for her shop, Maria General Store. Her program reads the name with scanf("%s"), as Module 3 taught, and every label says Maria. The other two words are not lost: they wait in the input. This lesson reads the whole name, and never writes past the end of an array.

Sign in to read

This lesson is free, with an account

An account costs nothing and opens every lesson in this track that is not marked Pro, on every device you read on.

What is inside Reading Strings Safely: fgets, and Why gets Was Removed

  1. %s reads one word, and the rest waits
  2. A width keeps %s inside its array
  3. fgets reads a whole line, newline included
  4. Removing the newline, only when it is there
  5. Reading line after line until fgets returns NULL
  6. A number, then a line: the leftover newline
  7. gets, the function C11 removed