📅  最后修改于: 2023-12-03 15:19:59.275000             🧑  作者: Mango
scanf("%[^\n]s", str)
vs gets(str)
in C with ExamplesIn C programming language, there are two standard ways to take input from the user for a string data type, using scanf("%[^\n]s", str)
and gets(str)
. Both have their own pros and cons.
scanf("%[^\n]s", str)
scanf("%[^\n]s", str)
is a formatted input function that reads input until it encounters a newline character \n
or an end-of-file (EOF) marker. It stores the input characters in the character array str
. The %[^\n]s
format specifier tells scanf
to read all characters except a newline character.
Example:
#include <stdio.h>
int main() {
char str[50];
printf("Enter your name: ");
scanf("%[^\n]s", str);
printf("Hello, %s!\n", str);
return 0;
}
Output:
Enter your name: John Doe
Hello, John Doe!
Pros:
%d
for integers, %f
for floats, etc.).scanf
allows us to read multiple variables in a single line of input.Cons:
fgets
or gets
.scanf
. For example, if we expect an integer but the user enters a string, the program can crash or behave unpredictably.scanf
can cause buffer overflow.gets(str)
gets(str)
is an unformatted input function that reads input until it encounters a newline character \n
or an end-of-file (EOF) marker. It stores the input characters in the character array str
, including the newline character.
Example:
#include <stdio.h>
int main() {
char str[50];
printf("Enter your name: ");
gets(str);
printf("Hello, %s!\n", str);
return 0;
}
Output:
Enter your name: John Doe
Hello, John Doe!
Pros:
scanf
.Cons:
fgets
or scanf
.In summary, scanf("%[^\n]s", str)
is best used for formatted input, where you want to specify a specific format for the input, and gets(str)
is best used for unformatted input, where you want to read input with spaces. However, both functions have their own drawbacks, so it is important to use them carefully and with caution. In general, it is recommended to use fgets
instead of gets
and scanf
for input in C programming language.