views:

961

answers:

4

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:~$
+3  A: 

The * is used to skip an input without putting it in any variable. So scanf("%*d %d", &i); would read two integers and put the second one in i.

The value that was output in your code is just the value that was in the uninitialized i variable - the scanf call didn't change it.

interjay
+6  A: 

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.

zacsek
+4  A: 

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.

Jon Cage
+9  A: 

For printf, the * allows you to specify minimum field width through an extra parameter, i.e. printf("%*d", 4, 100); specifies a field width of 4.

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

Håvard S