Again C language , Feel like learning again every time C Language has different feelings , There's a problem , namely scanf() This question , In fact, it's more detailed , There's a lot to dig into , In fact, every time we dig carefully , All right C A more thorough understanding of language .
So I'm right next scanf() Several methods of clearing input buffer in :
Application scenario : We use multiple scanf() When , If there is data in the input buffer , that scanf() You don't ask for user input , Instead, the contents of the input buffer are directly used , This causes the previous error to affect the later content , To isolate the problem ,
General idea : Read the contents of the input buffer in various ways .
Method 1 : use scanf(“%*[^\n]%*c”): success ; explain :
1. The asterisk here ’*’ Indicates reading in a certain type of content , But this content is not saved in the variable , So we don't need the corresponding parameters ;
in other words , As long as I % After asterisk , You can't leave the received variables behind .
2.scanf(“%*[^\n]%*c”) Of %*[^\n] Indicates that characters other than carriage returns are read in and not saved after a character is read in , That's all , It's not going to take me in , I can 't quit the program . But in this way it should %*s It should be OK , But no , I don't know why .
3. Inside is a read only restricted read character , as :[abcd] Read in only abcd Characters of
4. So the whole line of code is interpreted as "%*[^\n]" Read the rest of the buffer first ,%*c It's the last carriage return not read ; This clears the input buffer of .
Method 2 : use fflush(stdin) No success , The estimation is related to the mechanism of the system , Someone tested it vc yes ok Of , however xcode and linux No success under the system ;
Method 3 : use getchar+while success ; use while(getBuff=getchar()!=‘\n’ &&
getBuff!=EOF), Use the loop to read out the buffer , Until the \n Or null ; Method 4 : use gets+ Reserved maximum value succeeded ;
use gets, Create an array , Read the contents of the buffer ; Method 3, method 4 all use flow , Read the rest together , Whatever he is \n, This is more comfortable
Method 5 :rewind(stdin), This is in xcode sure , It's strange ,rewind It's OK to move the pointer to the beginning , Clear input is not allowed , It's amazing ;