Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

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

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
", str);

        printf("Enter interger: ");
        scanf("%*d", &i);
        printf("%d
", 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:~$
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...