Difference between scanf() and gets() in C
Last Updated :
13 Jun, 2022
- It is used to read the input(character, string, numeric data) from the standard input(keyboard).
- It is used to read the input until it encounters a whitespace, newline or End Of File(EOF).
For example see the following code:
C
#include <stdio.h>
int main()
{
char str[20];
printf ("enter something\n");
scanf ("%s", str);
printf ("you entered: %s\n", str);
return 0;
}
|
Here the input will be provided by the user and output will be as follows:
Input: Geeks for Geeks
Output: Geeks
Input: Computer science
Output: Computer
- It is used to read input from the standard input(keyboard).
- It is used to read the input until it encounters newline or End Of File(EOF).
C
#include <stdio.h>
int main()
{
char str[20];
printf ("enter something\n");
gets (str);
printf ("you entered : %s\n", str);
return 0;
}
|
Here input will be provided by user as follows
Input: Geeks for Geeks
Output: Geeks for Geeks
Input: Computer science
Output: Computer science
The main difference between them is:
- scanf() reads input until it encounters whitespace, newline or End Of File(EOF) whereas gets() reads input until it encounters newline or End Of File(EOF), gets() does not stop reading input when it encounters whitespace instead it takes whitespace as a string.
- scanf can read multiple values of different data types whereas gets() will only get character string data.
The difference can be shown in tabular form as follows:
scanf() |
gets() |
when scanf() is used to read string input it stops reading when it encounters whitespace, newline or End Of File |
when gets() is used to read input it stops reading input when it encounters newline or End Of File. It does not stop reading the input on encountering whitespace as it considers whitespace as a string. |
It is used to read input of any datatype |
It is used only for string input. |
Its syntax is -:
scanf(const char *format, …)
|
Its syntax is -:
char *gets(char *str)
|
It is fast to take input. |
It takes one parameter that is the pointer to an array of chars |
Format specifiers is used inside scanf to take input. |
Its return value is str on success else NULL. |
How to read complete sentence from user using scanf()
Actually we can use scanf() to read entire string. For example we can use %[^\n]s inside scanf() to read entire string.
C
#include <stdio.h>
int main()
{
char str[20];
printf ("Enter something\n");
scanf ("%[^\n]s", str);
printf ("%s", str);
return 0;
}
|
The above code reads the string until it encounters newline. Examples:
Input: Geeks for Geeks
Output: Geeks for Geeks
Input: Computer science
Output: Computer science
Share your thoughts in the comments
Please Login to comment...