Back to C Programming
2026-07-135 min read

Read and Write String: gets() and puts() (C Programming)

Learn Read and Write String: gets() and puts() (C Programming) step by step with clear examples and exercises.

Why This Matters

In this extensive guide, we delve into the essential C programming functions gets() and puts(), which are instrumental in reading and writing strings. These functions play a significant role in various real-world scenarios such as user input validation, error handling, and console output. Understanding their usage will not only enhance your coding skills but also provide you with a solid foundation for more advanced C programming tasks.

Prerequisites

To fully grasp the concepts presented in this tutorial, it is essential to have a firm understanding of the following topics:

  1. Basic C programming concepts (variables, data types, operators)
  2. Control structures (if-else statements, loops)
  3. Functions and function prototypes
  4. Arrays and pointers
  5. Understanding memory management in C
  6. Error handling and exception safety

Core Concept

gets() Function

The gets() function is a powerful tool for reading strings from the keyboard. It stores the input in a character array until it encounters the newline character (\n) or reaches the maximum size of the array. Here's an example that demonstrates its usage:

#include <stdio.h>

int main() {
char str[100];
printf("Enter a string: ");
gets(str);
puts(str);
return 0;
}

In this example, the gets() function reads a string from the user and stores it in the str array. The puts() function then outputs the stored string on the console.

Note: It is crucial to ensure that the size of the character array allocated for storing the input string is large enough to accommodate the expected input, as using an array with insufficient space may lead to undefined behavior and security vulnerabilities (buffer overflow).

Safe gets() Implementation

To avoid buffer overflow issues, it's a good practice to implement a safe version of the gets() function that limits the number of characters read:

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

void safe_gets(char *str, int size) {
fgets(str, size, stdin);
str[strcspn(str, "\n")] = '\0';
}

In this implementation, the fgets() function is used to read a string up to the specified size (including the newline character). The strcspn() function is then employed to remove the trailing newline character.

puts() Function

The puts() function is a simple yet effective way to display a string on the console. It takes a character pointer as its argument and outputs the contents of the pointed-to memory until it encounters the null character (\0). Here's an example that demonstrates its usage:

#include <stdio.h>

int main() {
char str[] = "Welcome to C programming!";
puts(str);
return 0;
}

In this example, the puts() function outputs the string stored in the str array on the console.

Worked Example

Let's create a simple program that reads a user's name using the safe gets() implementation and greets them using the printf() function:

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

void safe_gets(char *str, int size);

int main() {
char name[50];
printf("Enter your name: ");
safe_gets(name, sizeof(name));
printf("\nHello, %s!\n", name);
return 0;
}

void safe_gets(char *str, int size) {
fgets(str, size, stdin);
str[strcspn(str, "\n")] = '\0';
}

In this example, the safe_gets() function is used to read a string from the user and store it in the name array. The printf() function then outputs a personalized greeting using the stored input.

Common Mistakes

  1. Buffer Overflow: Using an array with insufficient space to store the input string can lead to buffer overflow, which may result in unexpected behavior or security vulnerabilities. To avoid this, always ensure that the character array allocated for storing the input is large enough to accommodate the expected input.
  2. Not checking for errors: The gets() function does not check for errors such as input truncation or end-of-file conditions. It's essential to handle these cases properly to prevent unexpected behavior in your program.
  3. Misusing puts() with formatted output: The puts() function should be used only for displaying strings, not for formatted output. For formatted output, use the printf() function instead.
  4. Using unsafe gets() implementation: Using the standard gets() function without bounds checking can lead to buffer overflow vulnerabilities. Always implement a safe version of gets() or use alternative functions like fgets().
  5. Not handling empty input: It's essential to handle cases where the user enters an empty string or presses Ctrl+D (End-of-file) instead of entering valid input.

Practice Questions

  1. Write a program that reads two strings from the user using the gets() function and compares them using the strcmp() function.
  2. Modify the worked example to handle cases where the user enters an empty string or presses Ctrl+D (End-of-file) instead of entering a name.
  3. Write a program that uses the puts() function to display a pattern like this:
*
**
**
**
**
**
**
*
  1. Implement a recursive version of the safe gets() function.
  2. Write a program that reads a line from the user using fgets(), removes any leading and trailing whitespace, and stores the result in a string variable.

FAQ

  1. Why is it dangerous to use gets() without checking the array size?

Using gets() with an array of insufficient size can lead to buffer overflow, which may result in unexpected behavior or security vulnerabilities.

  1. Can I use puts() for formatted output?

No, the puts() function is designed only for displaying strings, not for formatted output. For formatted output, use the printf() function instead.

  1. What happens if I exceed the array size while using gets()?

If you exceed the array size while using gets(), it may overwrite adjacent memory, leading to undefined behavior or security vulnerabilities (buffer overflow).

  1. Why is it important to handle empty input and end-of-file conditions when using gets()?

Handling empty input and end-of-file conditions is essential because they can cause your program to behave unexpectedly if not properly handled. For example, an empty string may lead to undefined behavior in certain contexts, while end-of-file indicates that the user has finished providing input and should be handled accordingly.

  1. What are some alternatives to the gets() function?

Some alternatives to the gets() function include fgets(), which allows you to specify a maximum number of characters to read, and safer implementations like the one presented in this tutorial. Another option is using a higher-level library or framework that provides more robust input handling capabilities.