Several Methods for clearing the input buffer in scanf () are summarized.
Application Scenario: when multiple scanf () instances are used, if there is data in the input buffer, scanf () will not ask the user for input, instead, the content of the input buffer is taken out for use. This causes the previous error to affect the subsequent content. to isolate this problem,
General idea: Read the content of the input buffer in various ways. method 1: Use scanf ("% * [^ \ n] % * c"): success; Explanation: 1. here, the asterisk '*' indicates reading a certain type of content, but this content is not saved to the variable, so corresponding parameters are not required; that is, as long as I add asterisks after %, no received variables can be placed. 2. the % * [^ \ n] % * [^ \ n] of scanf ("% * [^ \ n] % * c") indicates that characters other than carriage return and one character are not saved after being read, only in this way will I not input the carriage return to absorb it, so that I cannot exit the program. however, this method should also work for % * s, but not for sure. 3. [] indicates the characters that are read-only and read-only. For example, [abcd] indicates the characters that are read-only and read-only into abcd. therefore, the entire line of code is interpreted as "% * [^ \ n]" first reads the remaining content in the buffer, and % * c reads the last unread carriage return; in this way, the input buffer is cleared. method 2: failed to use fflush (stdin). It is estimated that it is related to the system mechanism. It is OK for someone to test vc, but xco Neither de nor linux is successful. Method 3: getchar + while is used. while (getBuff = getchar () is used ()! = '\ N' & getBuff! = EOF), use a loop to read the buffer until the \ n or null value of the buffer is read. Method 4: Use gets + to reserve the maximum value. Use gets to create an array, read the content of the buffer zone. Method 3 and method 4 Use the stream mode to read the rest of the content together, whether it is \ n or not, or this comfortable Method 5: rewind (stdin), which can be used in xcode. It's strange that rewind can move the pointer to the beginning, but cannot clear the input;