gets and puts in c

gets() and puts() in c

gets() in c

For entering string with whitespace we can use the function gets(). It is stop reading characters only when encounters a newline and replaces this newline by the null character. And all the characters entered by user stored in the character array. The null character is added to the array to make it a string and also gets() allows to user to input the space-separated strings.

Declaration

char[] gets(char[]);

Reading string using gets() function

/* Input and output strings usin gets() and puts() */
#include<stdio.h>
void main ()
{
char s[30];
printf("Enter any string ");
gets(s);
printf("entered String is %s",s);
}

Enter any string programmingknow is best
entered String is programmingknow is best

The gets() function may be harm or it is risky to use because it doesn’t perform any array bound checking and keep reading the characters until the new line (enter) is encountered, so it can be overflow, which can be avoided this by using fgets() we will learn about fgets() in next pages

puts() in c

we have another function puts() which can output a string and replaces the null character by a newline, The puts() function is very similar to printf() function as both work same, puts() is used to print the string on the console which is already read by using gets() or scanf() function, and the puts() returns an integer value that representing number of characters printed on the console

Declaration

int puts(char[])

/* Input and output strings usin gets() and puts() */
#include<stdio.h>
int
main()
{
char name[10];
printf("Enter the name");
gets(name);
printf("entered name is");
puts(name);
return 0;
}

The function gets can not check the buffer space, if the more input is provided by the user then the size of the array then it will be overwrite locations after the end of the array to avoid this we can use function fgets()

Enter the name programming know
entered name is programming know