The difference between scanf("%s")
and fgets
you've to keep in mind is the way they take in input.
%s
instructs scanf
to discard all leading whitespace characters and read in all non-whitespace characters until a whitespace character (or EOF
). It stores all the non-whitespace characters in its corresponding argument, in this case, yesNo
, and then leaves back the last whitespace character back into the standard input stream (stdin
). It also NUL-terminates its corresponding argument, in this case yesNo
.
fgets
reads in all input until a newline character ('
'
) or until the maximum number of characters to read passed in as the second argument minus one (for the NUL-terminator ''
) has been read (or until EOF
) and all this input, including the
, is stored in its first argument, yesNo
here, and it is NUL-terminated.
So, if you have scanf("%s", yesNo);
with an input of quit
, yesNo
will contain just quit
and the
will be left in the stdin
. Since the strings "quit"
and "quit
"
aren't the same, strcmp
will not return zero and the while
loop will continue to loop.
For fgets(yesNo, 6, stdin);
with the input quit
, yesNo
will hold quit
and the stdin
will be empty. strcmp
returns zero as both the strings "quit
"
and "quit
"
are equal, and execution comes out of the loop.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…