Ad Code

Responsive Advertisement

C gets() and puts() functions? With Example

 C gets() and puts() functions


The gets() and puts() are declared in the header file stdio.h. Both the functions are involved in the input/output operations of the strings.

1. gets() function:

The gets() function is used to read a line of text from the standard input (usually the keyboard) and store it as a string.
It reads characters from the standard input until a newline character ('\n') is encountered, and then it replaces the newline character with a null character ('\0') to terminate the string.

Example:
c
#include <stdio.h> 
int main() {
char str[50]; 
printf("Enter a string: "); 
 gets(str); 
printf("You entered: %s\n", str);
return 0;
 }

Note:The gets() function is considered unsafe because it does not check the size of the buffer, which can lead to buffer overflow issues. It is recommended to use safer alternatives like fgets().

2. 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 appends a newline character ('\n') after the string, so you don't need to explicitly add it.

Example:
c
#include <stdio.h>
int main()
char str[] = "Hello, World!";
puts("Using puts function:"); 
puts(str);
return 0;
 }


Output:
sql
Using puts function:
 Hello, World!

In this example, the puts() function is used to print the string "Hello, World!" to the console.

Important Note: 

As mentioned earlier, gets() is considered unsafe because it doesn't check the size of the buffer, making it susceptible to buffer overflow. It is highly recommended to use safer alternatives like fgets() for reading input. In practice, you may also consider using printf() instead of puts() for output to have more control over formatting.

Post a Comment

0 Comments