- 2072 Chaitra · 1 mark
Define and write syntax of gets()
Short answer
gets(str) reads a whole line including spaces from stdin into str, replacing newline with '\0'. It is unsafe because it lacks bounds checking and has been removed from modern C standards; use fgets instead.
Define and write syntax of gets().
gets() reads a whole line (a string, including spaces) from the keyboard into a character array and replaces the new line with '\0'. It is declared in <stdio.h>.
Syntax: gets(string_variable);
#include <stdio.h>
int main(void)
{
char name[30];
printf("Enter your full name: ");
gets(name);
printf("Hello, %s\n", name);
return 0;
}
Output (for the input Ram Bahadur Thapa):
Enter your full name: Hello, Ram Bahadur Thapa
gets() does not check the array size, so a long input overflows the array. It was removed in C11, and gcc warns that it is deprecated. The safe alternative is fgets(name, sizeof(name), stdin);.
✓ Answer checked by Claude Opus 5.5 (high effort)