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

后端 未结 2 1381
遥遥无期
遥遥无期 2021-01-20 00:17

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 scan

2条回答
  •  情书的邮戳
    2021-01-20 00:40

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

提交回复
热议问题