问题
I just had a test in my C class today and I have reason to believe that answer might be incorrect.
scanf("%d\n", &x); // Evaluate the expression for the string "54321\n"
The idea is pretty simplistic. Find an integer and place the scanned number at the memory location corresponding with integer variable x
. However, I don't believe that this call to scanf
would ever terminate.
As far as I am concerned, all calls to scanf
to standard I/O terminate with the press of the enter key, so there is no need to include the newline in the specifier string. In fact, this redundancy will only cause the program to stall in search of something that will never match the string.
Is there anyone who can clarify the technicalities of the scanf
function to put this problem to rest?
回答1:
I don't believe that this call to scanf would ever terminate.
6 character input like "54321\n"
is insufficient to cause this scanf("%d\n", &x);
to return. The program stalls. Something else must yet occur.
'\n'
directs scanf()
to consume white-spaces and to do so until
a non-white-space is detected.
stdin
is closedAn input error occurs on
stdin
(rare).
As stdin
is usually line buffered, scanf()
receives data in chunks.
The first chunk 123Enter is not enough to cause scanf("%d\n", &x);
to return. One of the 3 above needs to happen.
Any following input with some non-white-space fulfills #1, be it:
456Enter or
xyzEnter or
EnterEnter$Enter or ...
Then scanf()
will return with a 1 indicate a value, 123, was stored in x
. The 4, x or $ above was the non-white-space detected that caused completion. That character will be the next character read by subsequent input on stdin
.
scanf("%d\n", &x);
is almost certainly the wrong code to use as it obliges another line of user input and does not check its return value.
回答2:
all calls to scanf to standard I/O terminate with the press of the enter key, so there is no need to include the newline in the specifier string.
That's correct. The \n
in the format string will ignore any number of whitespaces, including the "ENTER" key; so, you'll have to input a non-whitespace char to terminate the scanf()
call. So, yes, the \n
is problematic.
scanf()'s man page says:
· A sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). This directive matches any amount of white space, including none, in the input.
By the way, scanf()
itself is considered problematic: Why does everyone say not to use scanf? What should I use instead?
来源:https://stackoverflow.com/questions/41767371/scanf-and-newlines-in-c