What are scanf("%*s") and scanf("%*d") format identifiers?

For printf, the * allows you to specify the minimum field width through an extra parameter, e.g. printf("%*d", 4, 100); specifies a field width of 4. A field width of 4 means that if a number takes less than 4 characters to print, space characters are printed until the field width is filled. If the number takes up more space than the specified field width, the number is printed as-is with no truncation.

For scanf, the * indicates that the field is to be read but ignored, so that e.g. scanf("%*d %d", &i) for the input "12 34" will ignore 12 and read 34 into the integer i.


The star is a flag character, which says to ignore the text read by the specification. To qoute from the glibc documentation:

An optional flag character `*', which says to ignore the text read for this specification. When scanf finds a conversion specification that uses this flag, it reads input as directed by the rest of the conversion specification, but it discards this input, does not use a pointer argument, and does not increment the count of successful assignments.

It is useful in situations when the specification string contains more than one element, eg.: scanf("%d %*s %d", &i, &j) for the "12 test 34" - where i & j are integers and you wish to ignore the rest.


See here

An optional starting asterisk indicates that the data is to be retrieved from stdin but ignored, i.e. it is not stored in the corresponding argument.