The differences of scanf(“%[^\n]”,name); and scanf(“ %[^\n]”,name);

前端 未结 2 475
夕颜
夕颜 2021-01-28 00:37

It\'s not a typo. And for the one who doesn\'t notice, there is a space on the second one, and no space on the first.

It happens to me when i make a homework like this:<

相关标签:
2条回答
  • 2021-01-28 01:07

    There are three standard format specifiers for the scanf() family of functions that do not automatically skip white space. They are:

    1. %c
    2. %[] — scan sets
    3. %n

    All other (standard) format specifiers skip leading white space.

    By including the white space before %[], you skip leading white space, because a single white space in the scanf() family format string (outside a scan set) matches zero or more white space characters in the input. Note, in particular, that this means that if you type some blank lines (just hit return), the white space will continue merrily ignoring (more accurately, discarding) the input until a non-white-space character is entered. Only then will scanf() start processing the scan set.

    0 讨论(0)
  • 2021-01-28 01:17

    When you put a space in a scanf formatting string, then scanf will match it with any whitespace, of any length. So by putting that leading space in the format, scanf will in effect skip leading whitespace in the input (which includes the newline from the previous input).

    Example:

    Lets say the input for your simple program is

    123
    Joe Bloggs
    22/9/15
    

    The first call to scanf read the number 123, but leaves the newline you enter to end that line of input in the input buffer. When you next call scanf to get the name, then scanf will first see that newline end return immediately (without consuming it, so it will still be in the input buffer). Then you call scanf to read the date, and the "%d" format automatically skip leading whitespace, so scanf will consume the newline, but then see the name and it will not match the format for decimal integers and exit, not reading the data.

    By adding that leading space to the format when reading the name, the second scanf call will read (and ignore) the newline from the previous input, and then read the name properly, leaving the terminating newline from the second line in the input buffer which is then skipped by the next call to scanf which properly reads the date.

    0 讨论(0)
提交回复
热议问题