gets() and puts() Functions in C

The gets() and puts() functions are used for handling input and output in C. These functions are part of the standard C library stdio.h. While gets() reads input from the user, puts() is used to display output on the console.

gets() Function

The gets() function is used to read a line of text (string) from the user input. It reads until a newline character is encountered, and then it stores the characters in the provided buffer. The function does not perform bounds checking, which can lead to buffer overflow if the input exceeds the buffer size. Therefore, it is considered unsafe and has been deprecated in modern C standards.

Syntax:

                        
char *gets(char *str);
                        
                    

Example: Using gets()

This example demonstrates how to use the gets() function to read a string from the user input and display it using puts().

Example Code:

                        
#include <stdio.h>
int main() 
{
    char name[100];
                
    // Reading input using gets()
    printf("Enter your name: ");
    gets(name);
                
    // Displaying input using puts()
    printf("Hello, ");
    puts(name);
                
    return 0;
}
                        
                    

Output

Enter your name: John Doe
Hello, John Doe

puts() Function

The puts() function is used to write a string to the standard output (usually the console) followed by a newline character. It automatically adds a newline after the string, so there is no need to use n explicitly.

Syntax:

                        
int puts(const char *str);
                        
                    

Example: Using puts()

This example demonstrates how to use the puts() function to display a string to the console.

Example Code:

                        
#include <stdio.h>
int main() 
{
    // Displaying output using puts()
    puts("Welcome to C programming!");
                
    return 0;
}
                        
                    

Output

Welcome to C programming!

Key Differences between gets() and puts()

Alternative to gets() - fgets()

Since gets() is considered unsafe, the fgets() function is recommended for reading strings from input. Unlike gets(), fgets() allows you to specify the buffer size, which prevents buffer overflow.

Example: Using fgets() instead of gets()

                        
#include <stdio.h>>
int main() 
{
  char name[100];
                
  // Reading input using fgets()
  printf("Enter your name: ");
  fgets(name, sizeof(name), stdin);
                
  // Displaying input using puts()
  printf("Hello, ");
  puts(name);
                
  return 0;
}
                        
                    

Output

Enter your name: John Doe
Hello, John Doe

Key Points