I have read all of the questions about these, but I have not found an explanation for the difference between %[^\n]s
and %[^\n]
in the scanf()
function.
The extra s
after %[^\n]
is a common mistake. It may come from a confusion between scansets and the %s
conversion specifier.
Its effect in a scanf
format string is a match for an s
byte in the input stream. Such a match will always fail because after the successful conversion of the %[^\n]
specifier, the stream is either at end of file or the pending character is a newline. Unless there are further conversion specifiers in the format string, this failure will have no effect on the return value of scanf()
so this bug is rarely an issue.
Note also these caveats:
%[^\n]
specifier will fail on an empty line.%[]
and %s
specifiers to avoid undefined behavior on unexpectedly large inputs.scanf("%99[^\n]", line)
will leave the newline pending in the input stream, you must consume it before you can read the next line with the same scanf
format string.Contrary to while (fgets(line, sizeof line, stdin)) { ... }
, you cannot simply write while (scanf("%99[^\n]", line) == 1) { ... }
to read the whole file line by line, you must consume the pending newline in the body of the loop and the loop would stop at the first empty line.
Example:
char line[100];
if (scanf("%99[^\n]", line) == 1) {
/* handle input line */
} else {
/* stream is at end of file or has an empty line */
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With