Gets and Puts in sting c programming

20 Sep 2022 Balmiki Mandal 0 C Programming

Understanding Gets and Puts Functions in C Programming

The gets() and puts() functions are used to read and write strings in C programming.

The gets() function reads a string from standard input (the keyboard) and stores it in the specified buffer. The function stops reading when it encounters a newline character (\n) or the end-of-file (EOF) character. The function then replaces the newline character with a null character (\0) and returns the buffer.

The puts() function writes the specified string to standard output (the console) and appends a newline character to the end of the string. The function returns the number of characters written, including the newline character.

Example of how to use the gets() and puts() functions:

C program
#include 

int main() {
  char name[10];

  // Read a string from the user.
  gets(name);

  // Write the string to the console.
  puts(name);

  return 0;
}

Output:

Enter your name: John Doe
John Doe

The gets() function is a deprecated function because it is not safe to use. The function can read past the end of the buffer, which can lead to buffer overflows and security vulnerabilities.

It is recommended to use the fgets() function instead of the gets() function. The fgets() function allows you to specify the maximum number of characters to read, which helps to prevent buffer overflows.

Example of how to use the fgets() function:

C program
#include 

int main() {
  char name[10];

  // Read a string from the user, with a maximum of 10 characters.
  fgets(name, 10, stdin);

  // Write the string to the console.
  puts(name);

  return 0;
}

The puts() function is a safe function to use. However, it is important to note that the function appends a newline character to the end of the string. If you do not want to append a newline character, you can use the printf() function instead.

Example of how to use the printf() function to write a string to the console without appending a newline character:

C Program
#include 

int main() {
  char name[10];

  // Read a string from the user.
  fgets(name, 10, stdin);

  // Write the string to the console, without appending a newline character.
  printf("%s", name);

  return 0;
}

The gets() and puts() functions are two powerful functions for reading and writing strings in C programming. However, it is important to use these functions carefully, especially the gets() function.

Top Resources

Further Reading:

 For further information and examples, Please visit[ C-Programming From Scratch to Advanced 2023-2024]

 

Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.