Player's guessing game (v2.2) (The scanf() function operation mechanism is revealed)

[Preliminary knowledge] The data entered by the user from the keyboard is saved in the buffer, and the input function does not read the data from the buffer until the user types the carriage return. The scanf() function reads the data in the buffer according to the specified format Data, if the reading fails, the non-numeric characters in the buffer will not be read. 

[Question raised] If we enter the alphabetic character'q' when the program starts to execute, how will the program execute?

    It can be seen from the execution result of the program that after entering the alphabetic character'q', the program directly completes a round of guessing (in the remaining 9 opportunities, the player cannot continue to enter the number). After the end of the round of guessing, The game ends without waiting for the player to choose: This is because after entering the alphabetic character'q', the character is saved in the buffer. Then we press the Enter key, the scanf() function reads the data from the buffer, but The data'q' in the buffer does not match the format character %d, so scanf() fails to read the data. Because the reading fails, the value of guess is still a random value. Although the reading fails, the illegal characters are still entered Stored in the buffer. If the value of guess (random number) and the value of magic are not equal, then the loop will not end (scanf() fails to read, the next round of the loop is still read, the result is still a failure, and so on Repeat ten times). After ten cycles, since the format character in scanf() is %c, which matches the character'q' in the buffer, read'q' away at this time, and then the variable flag The value is'q', this value does not meet the condition to continue the loop, so the program ends here. 

    If the character we input at the beginning is'Y', then the program will enter the next cycle after ten invalid cycles in this round, and wait for the user to input a value. This is because the ten invalid cycles in the first round

Guess you like

Origin blog.csdn.net/weixin_42048463/article/details/115183912