first of all, fscanf and fgets These two file functions of the concept of a deep understanding of the string input for the two functions have a typical difference is: fscanf read a space or carriage return will be converted to a blank space or enter/0(string terminator) and the Fgets function takes a space (the carriage return is explained below) as a character. There is an example of this:Charstr[ -];scanf ("%s", str); If you enter the following 12 characters , how is?carriage return actually does not add these 12 characters/0 is sent to the array str, but only the "how" before the space is sent to STR, because "how" as a string processing, so after adding/0. Now let's take a look at the first loop of the topic, using the Get function to accept strings. 1, enter "ABC return def". Now let's say the following fgets function for carriage return processing method. The definition of the Fgets function is this:Char*fgets (Char*s,intN,file *FP) When Fgets reads a carriage return, the function ends, and the carriage return is also fed as a word into the buffer of the parameter S point (note that the buffer is not memory), and the fgets () function sends a/0 characters, so that the character of the buffer is literal to the C string. That is, when the Fgets function reads the carriage return, it does not convert the carriage return in memory like the FSCANF function ./0, but is handled in the buffer. The result of this processing is that the carriage return does not work, that is, when we enter the ABC return DEF, abcdef in memory is continuously stored. Therefore, the second loop output will naturally not wrap. 2, enter "I AM A STUDENT" and add a space between the characters. In the first loop, the result of reading with Fgets is "I AM A STUDENT" and the space is treated as a character. Then in the second loop, after reading "I AM A STUDENT" with fscanf, the spaces in the string are converted to/0, a string is divided into four"I" "AM" "A" "STUDENT"。 Here may be someone to ask, so since the addition of/0, why does the loop continue to read/0? Note that the end condition of the loop is EOF (end of file) instead of/0(file terminator). First time output"I"Encountered/0 output return end, continue to determine the loop condition found file does not end, then continue to output"AM"and carriage return .... One until"STUDENT"Enter. Add a question if you want to make"I" "AM" "A" "STUDENT"output on the same line how should the program change? The answer is: fscanf replaced with fgets (FP, str).
FSCANF and Fgets usage