Difference between scanf() and gets() in C Language

Both functions scanf() and gets() are used to read the input from standard input (keyboard) But, there are differences in how they treat the input.

scanf() Functiongets() Function
Signature of sanf() function
int scanf ( const char * format, … );
Signature of gets() function
char * gets ( char * str );
scanf() reads the data from the standard input(stdin). Data that is read from standard input can be of multiple values of different data types get() reads the characters from the standard input(stdin)
scanf() reads the input until whitespace, newline, tab or End of File(EOF) is encounter gets() reads the input until newline(\n) or End Of File(EOF) is encountered
Can read multiple values of different typesCan only read character string data
It stops reading from standard input when white spaces are encounteredgets() considers white spaces part of the input and doesn’t reading when white spaces are encountered
On success, scanf() returns the number of arguments are from argument list are successfully filled. This count can be less than are equal to number of arguments excluding format string(1st argument) or less. Return value an be zero due to input data matching failure, reading error or EOFOn success, this function return the string. In case if it failed to read the string
Format string is passed a first argument with format specifiers to specify type and format of the data. Retrieved data is stored into locations pointed by following argumentsgets() takes only one argument which would character array or pointer to character to store input read from standard input
Example:

int x;
float price;
char name[32] ;
scanf(“%d %f, %s”, &x, &price, name);
Example:

char str[100];
gets(str);
scanf () can also be used to read entire string including spaces using negated scanset

char str[100];
scanf(“%[^\n]s”, str);
gets() cannot be used to read any other data types except string
scanf() is general purposegets() is dedicated for reading character string data
scanf if vulnerable to “format string attacks”
Other similar functions like scanf() are scanf(), fscanf()
Other similar functions like gets() are fgets, getc, and gethcar
Differences between scanf() and gets() function in C Language

Default image
neotam
Naveen T aka neotam. Programming language agnostic, Software architect, Python expert, Networking & DevOps engineer & consultant with 7+ years of experience in creating serious web applications, real time event-driven non blocking applications and database driven applications ranging from small scale to enterprise grade. website
Leave a Reply