Gets and Puts in C
Gets and Puts
gets()
andputs()
are two C library functions that are used for input and output of strings, respectively.Both
gets()
andputs()
functions are part of thestdio.h
header file, which is included at the beginning of the program.
Gets
The
gets()
function reads a line of text from stdin (standard input) and stores it in a string variable.The
gets()
function takes a single argument, which is a pointer to a character array that will hold the input string.The function reads characters from
stdin
and appends them to the input string until a newline character(\n)
is encountered.The input string is automatically null-terminated.
Puts
The
puts()
function writes a null-terminated string tostdout
(standard output) and adds a newline character at the end of the string.The
puts()
function takes a single argument, which is a pointer to a null-terminated character array (string). The function writes the string to stdout followed by a newline character(\n)
.
It should be noted that the use of
gets()
function is discouraged due to potential security risks.The
fgets()
function is a safer alternative for reading input strings fromstdin
.
The syntax for gets()
and puts()
is:
char *gets(char *str);`gets()`
int puts(const char *str);
Example
Following C program uses gets()
and puts()
functions to read input strings and write them back to the console:
#include <stdio.h>
#define MAX_LENGTH 100
int main() {
char input[MAX_LENGTH];
printf("Enter a message: ");
gets(input);
printf("You entered: ");
puts(input);
return 0;
}
Explanation:
- We first declare a character array input of size
MAX_LENGTH
. We then print a message to the console usingprintf()
function, asking the user to enter a message. - We then use the
gets()
function to read a line of text fromstdin
and store it in the input array. - Next, we use the
puts()
function to write the input string back to the console, followed by a newline character.
When this program is run, the user is prompted to enter a message. Once they enter the message and press Enter, the program reads the input string and echoes it back to the console.
Output:
Enter a message: Hello, World!
You entered: Hello, World!
The user entered the message "Hello, World!" and the program echoed the message back to the console.
Note that the puts()
function automatically adds a newline character at the end of the string.