简体   繁体   中英

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

我已经阅读了有关这些的所有问题,但我没有找到解释scanf()函数中%[^\\n]s%[^\\n]之间的区别。

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 */
}

Adding [^\\n ] in scanf() means skip over any new line char. It consumes all apart from new line char.

The the * flag signals that no assignment should be made. In this case * char. [\\n] skips over any leading newline characters

In other words: %*[^\\n] scans means everything until a \\n(Doesn't scan \\n) and discards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM