the difference between fgets and scanf1. An example of testing using scanf:
[CPP]View Plaincopyprint?
- #include "stdio.h"
- #include "string.h"
- int main ()
- {
- Char name[10];
- scanf ("%s", name);
- puts (name);
- return 0;
- }
Compile and invoke the following:
Can see the second time, due to the input string length, resulting in abort
2, the same example of a fgets:
[CPP]View Plaincopyprint?
- #include "stdio.h"
- #include "string.h"
- int main ()
- {
- Char name[10];
- Fgets (name, ten, stdin);
- puts (name);
- return 0;
- }
Compile and invoke the following:
There is no case of abort like scanf, but a truncation of the string
3. Compare scanf and Fgets:
A) scanf does not restrict user input, resulting in the abort of the above test example
Fgets restricts the user's input, and then truncates the string, avoiding abort, but setting a buffer length value
b) scanf can be used such as scanf ("%d/%d", &x, &y) in such a way that the user only needs to enter 1/3 to get the values of x and Y respectively:
[CPP]View Plaincopyprint?
- #include "stdio.h"
- int main ()
- {
- int x;
- int y;
- scanf ("%d/%d", &x, &y);
- printf ("x value:%d, y value:%d\n", x, y);
- return 0;
- }
But fgets, in any case, can only read one variable at a time, and it can only be a string (after all, it's str!). ), as in the following form, compilation is not a pass:
[CPP]View Plaincopyprint?
- #include "stdio.h"
- int main ()
- {
- int x;
- Fgets (x, sizeof (x), stdin);
- printf ("x value:%d", x);
- return 0;
- }
c) spaces in the string
When scanf receives a string with%s, it stops when it encounters a space. If you want to enter multiple words, you need to call scanf () multiple times
Fgets () directly receives spaces in a string
4. Summary
Due to some of the differences mentioned in 3, be aware of the situation when using scanf () and fgets ().
The difference between fgets and scanf