% S of the input string

Example

#include <stdio.h>

int main()
{
    int no;
    char name1[15], name2[15], name3[15];

    printf("Enter no and name1:\n");
    scanf("%d %15c", &no, name1);
    printf("%d %15s \n\n", no, name1);

    printf("Enter no and name2:\n");
    scanf("%d %s", &no, name2);
    printf("%d %15s \n\n", no, name2);

    printf("Enter no and name3:\n");
    scanf("%d %15s", &no, name3);
    printf("%d %15s \n\n", no, name3);

    return 0;
}

Output

Question

1, after the second input is completed, press Enter, the routine ends directly. Why would automatically ignore the third output?
2. Why output York?

『Notice』

When a character specifier% s, the event space, a read operation will be terminated.
scanf input data from the read data line, ignored whitespace : space, tab, newline.

Answer

① First, we tested another set of inputs

By comparing the two sets of inputs, we found that, when faced with the character does not match the character description when user input, scanf will be matched automatically. The integer number assigned to% d, character type variable is assigned to% s indicates, while between these two strings are spliced together and if there is a space independent .

② through debugging, we found that can make scanf early termination , there are two conditions, one can be satisfied:

  1. If the field width is specified, reads the number of characters reaches a specified width. (E.g.,% 15c, the number of input characters reaches 15)
  2. I encountered an illegal character when reading. (E.g.,% d, a character is inputted Y)

Guess you like

Origin www.cnblogs.com/zhyantao/p/11330534.html