Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between scansets in scanf() function?

Tags:

c

scanf

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.

like image 758
Zahra19977 Avatar asked Mar 06 '23 05:03

Zahra19977


1 Answers

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:

  • the %[^\n] specifier will fail on an empty line.
  • it is safer to always specify the maximum number of bytes to convert for the %[] 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 */
}
like image 131
chqrlie Avatar answered Mar 10 '23 10:03

chqrlie