Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between scanf() and gets() in C
In C programming, both scanf() and gets() functions are used to read input from the user. However, they handle input differently and have distinct characteristics that make them suitable for different scenarios.
Syntax
int scanf(const char *format, ...); char *gets(char *str);
Important Note: The
gets()function has been removed from the C11 standard due to security vulnerabilities. It is recommended to usefgets()instead.
Key Differences
| Sr. No. | Aspect | scanf() Function | gets() Function |
|---|---|---|---|
| 1 | Input Reading | Reads input according to format specifiers and stops at whitespace, newline, or EOF | Reads entire line including spaces until newline or EOF is encountered |
| 2 | Whitespace Handling | Treats whitespace as delimiter and stops reading when encountered | Includes whitespace as part of the input string |
| 3 | Data Types | Can read multiple data types (int, float, char, etc.) using format specifiers | Only reads character strings |
| 4 | Buffer Overflow | Can cause buffer overflow if input exceeds expected size | Highly prone to buffer overflow attacks (major security risk) |
| 5 | Return Value | Returns number of successfully read items | Returns pointer to the string or NULL on error |
Example: Comparing scanf() and gets()
The following example demonstrates how scanf() handles whitespace differently than gets() −
#include <stdio.h>
int main() {
char name1[50];
char name2[50];
printf("Enter your full name using scanf: ");
scanf("%s", name1);
/* Clear input buffer */
while(getchar() != '<br>');
printf("Enter your full name using gets: ");
gets(name2);
printf("\nUsing scanf: %s<br>", name1);
printf("Using gets: %s<br>", name2);
return 0;
}
Enter your full name using scanf: John Doe Enter your full name using gets: John Doe Using scanf: John Using gets: John Doe
Safer Alternative: Using fgets()
Since gets() is deprecated, here's how to use fgets() as a safer alternative −
#include <stdio.h>
#include <string.h>
int main() {
char input[100];
printf("Enter text: ");
fgets(input, sizeof(input), stdin);
/* Remove newline character if present */
input[strcspn(input, "<br>")] = '\0';
printf("You entered: %s<br>", input);
return 0;
}
Enter text: Hello World You entered: Hello World
Conclusion
While scanf() is suitable for reading formatted input of various data types, gets() was designed for reading entire lines but is now deprecated due to security risks. Use fgets() instead of gets() for safe string input in modern C programming.
