(1) First look at a program :
Found a problem : "scanf() function eats the following data " .
(2) When the scanf() function receives data , it will end the input of a data in the following cases :
①In case of space, carriage return, and tab key .
② When the width ends .
③ In case of illegal input .
* So in the above example, the scanf() function that encounters a space will consider it to be the end of the assignment to str1 , and ignore the following "love you", but "love you" is still in the keyboard buffer ,
(3) Test procedure :
#include<stdio.h> #include<windows.h>
intmain() { char str1[90]; char str2[90]; char str3[90]; scanf("%s",&str1); printf("%s\n",str1);
Sleep(5000); // To pause the program for 5000 milliseconds
scanf("%s",&str2); // Not used for input , it is to let the program scan the keyboard buffer again scanf("%s",&str3); // Not used for input , it is to let the program scan the keyboard buffer again
printf("%s\n",str2); printf("%s\n",str3);
return 0; } |
When inputting "i love you" , the program will output "i" first, and after an interval of 5000 milliseconds, the program will continue to output "love you".
( input "i love you" will only output "i" at first)
( After waiting for 5000 milliseconds , the program will output "love you")
* All the input of the keyboard is in the cache , but the scanf function uses the first space as the end symbol of the data assignment. When multiple scanfs are used to scan the buffer later , all the buffered data can be obtained and assigned . to the variable .
(4) By the way, mention the empty buffer operation :
① fflush(stdin);
② rewind(stdin);
* If any of the above two are placed after Sleep(5000) , the program will only output "i", and the next two scanf() will not scan the data in the buffer , but will only wait for the user's input two time to end the program .
(5) "%[] scan character set " :
a. This character set is a type of scanf format control , similar to "%d", "%c", and the brackets are for matching
The content , such as "%[az]", is to match lowercase English letters ;
It should be noted that such a match is only searched from the front to the back of all the characters in the input , starting from the first character
It will continue to search only if it meets the matching requirements , and if it does not meet the requirements, it will end the scanf function directly , so
As long as it does not match at the beginning, it is equivalent to no input .
b. You can also use "^", the effect of using "^" is to limit the end point of the acquisition , such as "%[^a123]", if the input
Enter "sdfddgadasdsada123sdfdsfjsdjf", after matching, only "sdfddg" will be used as the input content , so
The known effect is to use any character in the brackets as the end point of the end :
The biggest use of this format is to solve the above phenomenon of "scanf eats spaces " , which can not only limit the process
All characters before a certain character are used as a data value :