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() Function | gets() 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 types | Can only read character string data |
It stops reading from standard input when white spaces are encountered | gets() 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 EOF | On 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 arguments | gets() 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 purpose | gets() 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 |