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()andfgets()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()andprintf().
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.
| Function | Job | Safe? | Note |
|---|---|---|---|
gets(str) | Reads a line | No | No size limit. Removed in C11; do not use |
fgets(str, size, stdin) | Reads a line | Yes | Reads at most size − 1 characters; keeps the '\n' |
puts(str) | Prints a string | Yes | Adds 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 fgets | Meaning |
|---|---|
array_name | Where to store the text |
size | Size of the array (usually sizeof(array_name)) |
stdin | Standard 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
char name[50];: an array that can hold up to 49 characters plus the ending'\0'.fgets(name, sizeof(name), stdin);: reads the whole line, spaces included, but never more than 49 characters.- fgets also stores the Enter key, so
namebecomes"Riya Sharma\n". strcspn(name, "\n")finds the position of'\n', and we replace it with'\0'(end of string). Nownameis"Riya Sharma".- 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
| Mistake | What happens | Fix |
|---|---|---|
Using gets() | Warning/error; risk of buffer overflow | Use fgets() |
Forgetting fgets keeps '\n' | Output breaks onto the next line | Remove it with strcspn |
fgets(name, 100, stdin) with char name[50] | Can overflow the array | Use sizeof(name) |
Calling fgets right after scanf("%d") | fgets reads the leftover Enter and gets an empty line | Clear the newline first (see the scanf problems lesson) |
gets(), puts() and fgets() Practice Questions
- Why is
gets()dangerous? - Write the syntax of
fgets()and explain each part. - What is the difference between
puts()andprintf()? - Why does
fgets()read only size − 1 characters? - How do you read a sentence with spaces in C?
Show answers
- It does not check the array size, so long input causes a buffer overflow. It was removed in C11.
fgets(str, size, stdin):stris where to store,sizeis the array size,stdinis the keyboard.puts()prints only a string and adds a new line automatically;printf()can print formatted values and needs\n.- To leave one place for the
'\0'that ends the string. - 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)
-
Which function was removed from C11 because it is unsafe?
A)
fgets()B)puts()C)gets()D)printf() -
puts("Hi");prints:A) Hi with no new line B) Hi and a new line C) "Hi" D) Error
-
In
fgets(s, 20, stdin), the maximum characters read are:A) 20 B) 19 C) 21 D) Unlimited
-
stdinmeans:A) Screen B) Keyboard (standard input) C) A file named stdin D) Printer
-
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
- C:
gets() - B: Hi and a new line.
- B: 19 (one place for
'\0'). - B: keyboard (standard input).
- 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 most | size − 1 characters |
| fgets keeps | The '\n' |
| puts() | Prints string + new line |
| scanf("%s") | Stops at a space |
| Problem with gets | Buffer 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.