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

manav m-n picture manav m-n · Jan 28, 2010 · Viewed 72.8k times · Source

What is the practical use of the formats "%*" in scanf(). If this format exists, there has to be some purpose behind it. The following program gives weird output.

#include<stdio.h>
int main()
{
        int i;
        char str[1024];

        printf("Enter text: ");
        scanf("%*s", &str);
        printf("%s\n", str);

        printf("Enter interger: ");
        scanf("%*d", &i);
        printf("%d\n", i);
        return 0;
}

Output:

manav@workstation:~$ gcc -Wall -pedantic d.c
d.c: In function ‘main’:
d.c:8: warning: too many arguments for format
d.c:12: warning: too many arguments for format
manav@manav-workstation:~$ ./a.out
Enter text: manav
D
Enter interger: 12345
372
manav@workstation:~$

Answer

H&#229;vard S picture Håvard S · Jan 28, 2010

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.