What is the Difference Between scanf and gets?

🆚 Go to Comparative Table 🆚

The main difference between scanf() and gets() in C programming lies in their input handling behavior:

  • scanf():
  • Reads input until it encounters whitespace, newline, or End Of File (EOF).
  • Can read multiple values of different data types.
  • Syntax: scanf(const char *format, …).
  • Flexible and can be used for various data types.
  • gets():
  • Reads input until it encounters newline or EOF, considering whitespace as part of the input.
  • Used only for string input.
  • Syntax: char *gets(char *str).
  • Less flexible and can only handle character strings.

scanf() is a more versatile function compared to gets(), as it can read multiple values of different data types and is used for various data types. On the other hand, gets() is used exclusively for reading character strings and has been removed from the C language due to safety concerns, as it does not provide protection against buffer overruns. It is recommended to use fgets() instead, as it allows for safely processing input lines of any length.

Comparative Table: scanf vs gets

Here is a table comparing the differences between scanf and gets:

Feature scanf gets
Purpose Reads input until it encounters whitespace, newline, or End Of File (EOF). Reads input until it encounters newline or End Of File (EOF).
Input Format Accepts multiple values of different data types. Only reads character string data.
Data Reading Stops reading input when whitespace is encountered. Considers whitespace as part of the input and does not stop reading when encountered.
Return Returns the number of arguments successfully filled, which can be zero due to input data matching failure, reading error, or EOF. Returns a string on success or indicates failure if it fails to read the string.
Syntax scanf(const char *format, …). char *gets(char *str).

Note that gets has been removed from the C language due to security concerns, as it was both superfluous and dangerous, with no protection against buffer overruns. Instead, the C standard recommends using fgets for safer input processing.