2) When
%9[a]
failed at b,scanf
didn't exit. It simply went on scanning further input.
Yes, the %9[a]
directive means "store up to 9 'a'
s, but at least one"(1), so the conversion %9[a]
did not fail, it succeeded. It found fewer 'a'
s than it could have consumed, but that's not a failure. The input matching failed at the 'b'
, but the conversion succeeded.
(1) Specified in 7.21.6.2 (12) where the conversions are described:
[
Matches a nonempty sequence of characters from a set of expected characters (the scanset).
Now for input book,
%9[a]
should fail at b from the book and should store just'\0'
at line1 since here nothing was parsed. Then%9[^\n]
should parse the remaining line and should store just now parsedbook+\0
at line2.
No. It is supposed to exit when a conversion fails. The first conversion %9[a]
failed, so scanf
is supposed to stop and return 0, since no conversion succeeded.
Always check the return value of scanf
.
That is specified (for fscanf
, but scanf
is equivalent to fscanf
with stdin
as input stream) in 7.21.6.2 (16):
The
fscanf
function returns the value of the macroEOF
if an input failure occurs before the first conversion (if any) has completed. Otherwise, the function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.Here output for
line1
is nothing which is exactly what we expected. An empty string!
You can't expect anything. The arrays line1
and line2
aren't initialised, so when the conversion fails, their contents is still indeterminate. In this case, line1
contained no printable character before the first 0 byte.
But for
line2
it's garbage chars! We didn't expect this. So how did this happen ?
That's what happened to be the contents of line2
. There were never any values assigned to the elements, so they are whatever they happened to be before the call to scanf
.