gets() and puts() in C
0 375
gets in C
In C programming, gets() is a function that reads a line of text from the standard input (usually the keyboard) and stores it as a string.
However, it's considered risky because it doesn't check the length of the input, potentially leading to buffer overflow issues.
Syntax of gets()
char *gets(char *str);
str: A pointer to the character array where the input string will be stored.
This character array should have enough space to hold the input string.
The gets() function doesn't return anything.
It directly reads characters from the standard input until a newline character ('\n') is encountered or the end-of-file (EOF) condition is reached, and stores them in the specified character array str.
Then, it appends a null character ('\0') to terminate the string.
For example:
// Program for gets() function
#include<stdio.h>
int main() {
char str[50];
printf("Enter a string: ");
gets(str); // Read input from user
printf("You entered: ");
puts(str); // Display the string
return 0;
}
Output:
Enter a string: r
You entered: r
In this example, gets() reads the user input into the str array.
However, if the input exceeds the size of the array, it can overwrite memory, leading to unpredictable behavior or security vulnerabilities.
puts in C
puts() is a safer alternative for outputting strings.
It simply prints the string to the standard output (usually the screen) and appends a newline character.
In C programming, the puts() function is used to write a null-terminated string to the standard output (usually the console or terminal).
It appends a newline character ('\n') after printing the string.
Syntax of puts()
int puts(const char *str);
str: A pointer pointing to the null-terminated string that is to be written.
The puts() function returns a non-negative integer on success, and EOF (End of File) on failure.
The puts() function returns a non-negative integer on success, and EOF (End of File) on failure.
For example:
// Program for puts functionOutput:
#include<stdio.h>
int main() {
char str[] = "Hello, world!"; // A null-terminated string
puts(str); // Output the string to the console with a newline
return 0;
"Hello, world!"
We use the puts() function to print the string to the standard output, followed by a newline character ('\n').
The string "Hello, world!" is displayed on the console followed by a newline.
Visual Diagram for gets() and puts() Functions in C
Share:
Comments
Waiting for your comments