Skip to content
StudyFame

gets(), puts() and fgets() in C

scanf("%s") stops reading at the first space. So if you type Riya Sharma, it only gets Riya. How do you read a full line with spaces?

In this lesson you will learn fgets() to read a line, puts() to print a line, and why the old gets() function is dangerous and was removed from C.

What You Will Learn

  • What gets(), puts() and fgets() do.
  • Why gets() is unsafe and was removed in C11.
  • How to read a line safely with fgets().
  • How to remove the extra newline that fgets() keeps.
  • The difference between puts() and printf().

gets(), puts() and fgets() Explained

Exam definition: gets() reads a line of text (with spaces) from the keyboard, puts() prints a string followed by a new line, and fgets() reads a line safely, with a size limit. All three are unformatted string I/O functions in stdio.h.

FunctionJobSafe?Note
gets(str)Reads a lineNoNo size limit. Removed in C11; do not use
fgets(str, size, stdin)Reads a lineYesReads at most size − 1 characters; keeps the '\n'
puts(str)Prints a stringYesAdds a new line automatically

Memory trick: gets is a glass with no limit: pour too much and it overflows. fgets is a glass with a size: it stops before overflowing. The extra f is for file, because it can read from any input, including stdin (the keyboard).

Why is gets() dangerous?

  • gets() does not know how big your array is.
  • If the user types more characters than the array can hold, it writes past the end of the array into other memory. This is called a buffer overflow.
  • Hackers have used this bug to break into programs. So gets() was deprecated in C99 and removed in C11. Modern compilers give a warning or an error.

Syntax of fgets() and puts()

fgets(array_name, size, stdin);   /* read a line, at most size - 1 characters */
puts(string);                     /* print the string and a new line */
Part of fgetsMeaning
array_nameWhere to store the text
sizeSize of the array (usually sizeof(array_name))
stdinStandard input, which means the keyboard

Example 1: Read a Full Name with fgets()

#include <stdio.h>
#include <string.h>

int main(void)
{
    char name[50];

    printf("Enter your full name: ");
    fgets(name, sizeof(name), stdin);

    name[strcspn(name, "\n")] = '\0';   /* remove the newline */

    printf("Hello, %s!\n", name);
    return 0;
}

Output

Enter your full name: Riya Sharma
Hello, Riya Sharma!

Code Explanation

  1. char name[50];: an array that can hold up to 49 characters plus the ending '\0'.
  2. fgets(name, sizeof(name), stdin);: reads the whole line, spaces included, but never more than 49 characters.
  3. fgets also stores the Enter key, so name becomes "Riya Sharma\n".
  4. strcspn(name, "\n") finds the position of '\n', and we replace it with '\0' (end of string). Now name is "Riya Sharma".
  5. Without that line, the ! would print on the next line.

How fgets() Works

  • It reads characters one by one from the input buffer.
  • It stops when it reads a newline, or when it has read size − 1 characters, or at end of input.
  • It always adds '\0' at the end, so the result is a proper string.
  • If the line is too long, the extra characters stay in the buffer for the next read. Your array is never overflowed.

Example 2: puts() vs printf()

#include <stdio.h>

int main(void)
{
    char city[] = "Pune";

    puts("Welcome!");          /* adds a new line by itself */
    puts(city);
    printf("City: %s\n", city);  /* printf needs \n */

    return 0;
}

Output

Welcome!
Pune
City: Pune

puts() is simpler when you only want to print a string on its own line. Use printf() when you need to mix text with values.

Important Points to Remember

  • gets() is unsafe and was removed in C11.
  • Use fgets(str, size, stdin) to read a line with spaces.
  • fgets() keeps the '\n'; remove it if needed.
  • puts() adds a new line automatically.
  • scanf("%s") stops at a space.

Common Mistakes Beginners Make

MistakeWhat happensFix
Using gets()Warning/error; risk of buffer overflowUse fgets()
Forgetting fgets keeps '\n'Output breaks onto the next lineRemove it with strcspn
fgets(name, 100, stdin) with char name[50]Can overflow the arrayUse sizeof(name)
Calling fgets right after scanf("%d")fgets reads the leftover Enter and gets an empty lineClear the newline first (see the scanf problems lesson)

gets(), puts() and fgets() Practice Questions

  1. Why is gets() dangerous?
  2. Write the syntax of fgets() and explain each part.
  3. What is the difference between puts() and printf()?
  4. Why does fgets() read only size − 1 characters?
  5. How do you read a sentence with spaces in C?
Show answers
  1. It does not check the array size, so long input causes a buffer overflow. It was removed in C11.
  2. fgets(str, size, stdin): str is where to store, size is the array size, stdin is the keyboard.
  3. puts() prints only a string and adds a new line automatically; printf() can print formatted values and needs \n.
  4. To leave one place for the '\0' that ends the string.
  5. With fgets(str, sizeof(str), stdin).

Coding Exercise

Ask the user for their favourite movie name (it may have spaces), remove the newline, and print it with puts() after the text Your favourite movie is:.

Show solution
#include <stdio.h>
#include <string.h>

int main(void)
{
    char movie[100];

    printf("Favourite movie: ");
    fgets(movie, sizeof(movie), stdin);
    movie[strcspn(movie, "\n")] = '\0';

    puts("Your favourite movie is:");
    puts(movie);
    return 0;
}
Favourite movie: The Lion King
Your favourite movie is:
The Lion King

Quick Quiz: gets(), puts() and fgets() (MCQ)

  1. Which function was removed from C11 because it is unsafe?

    A) fgets()   B) puts()   C) gets()   D) printf()

  2. puts("Hi"); prints:

    A) Hi with no new line   B) Hi and a new line   C) "Hi"   D) Error

  3. In fgets(s, 20, stdin), the maximum characters read are:

    A) 20   B) 19   C) 21   D) Unlimited

  4. stdin means:

    A) Screen   B) Keyboard (standard input)   C) A file named stdin   D) Printer

  5. What does fgets() store at the end of a line that fits?

    A) Nothing   B) '\n' then '\0'   C) Only '\0'   D) A space

Show answers
  1. C: gets()
  2. B: Hi and a new line.
  3. B: 19 (one place for '\0').
  4. B: keyboard (standard input).
  5. B: the newline, then the null character.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

gets()Reads a line, unsafe, removed in C11
fgets()fgets(str, size, stdin), safe
fgets reads at mostsize − 1 characters
fgets keepsThe '\n'
puts()Prints string + new line
scanf("%s")Stops at a space
Problem with getsBuffer overflow

Frequently asked questions

What is the difference between gets() and fgets()?
gets has no size limit (unsafe, removed); fgets takes a size limit and also keeps the newline.
What is a buffer overflow?
Writing more data than an array can hold, so it spills into other memory.
What is the difference between puts() and printf()?
puts prints only a string and adds a new line; printf prints formatted values.
How do you remove the newline from fgets input?
str[strcspn(str, "\n")] = '\0';

Remember

  • gets = glass with no limit (overflows); fgets = glass with a size.
  • Never use gets().

Next Topic

Next lesson: Formatted and Unformatted I/O in C. You will compare all the input/output functions and learn which are formatted and which are not.