6

I typically acquire a character with %c, but I have seen code that used %*c%c. For example:

char a;
scanf("%*c%c", &a);

What is the difference?

Greg Bacon
  • 134,834
  • 32
  • 188
  • 245
ild0tt0re
  • 75
  • 7
  • 1
    Each of the specifiers is described in any decent book. Did you consider one before posting? – dirkgently Jun 19 '12 at 21:32
  • 2
    yes, I've tried to find but i found other cases. My book explay these char %c short, int, long %d short, int, long %i unsigned short, unsigned int, unsigned long %u float %f double %lf float, double (notazione scientifica) %e float, double [usa il più breve tra %f e %e] %g short, int, long (formato ottale) %o short, int, long (formato esadecimale) %x puntatore %p sequenza di caratteri terminata da un '\0' %s unsigned long long [64-bit] %llu long long [64-bit] %ll long double [64-bit] %Lf unsigned short [8-bit] %hu Can you explain me the difference? please – ild0tt0re Jun 19 '12 at 21:38
  • Does this answer your question? [What are scanf("%\*s") and scanf("%\*d") format identifiers?](https://stackoverflow.com/questions/2155518/what-are-scanfs-and-scanfd-format-identifiers) – dgnuff Feb 19 '23 at 09:10

3 Answers3

7

In a scanf format string, after the %, the * character is the assignment-suppressing character.

In your example, it eats the first character but does not store it.

For example, with:

char a;
scanf("%c", &a);

If you enter: xyz\n, (\n is the new line character) then x will be stored in object a.

With:

scanf("%*c%c", &a);

If you enter: xyz\n, y will be stored in object a.

C says specifies the * for scanf this way:

(C99, 7.19.6.2p10) Unless assignment suppression was indicated by a *, the result of the conversion is placed in the object pointed to by the first argument following the format argument that has not already received a conversion result.

ouah
  • 142,963
  • 15
  • 272
  • 331
5

According to Wikipedia:

An optional asterisk (*) right after the percent symbol denotes that the datum read by this format specifier is not to be stored in a variable. No argument behind the format string should be included for this dropped variable.

It is so you can skip the character matched by that asterisk.

Nick
  • 4,901
  • 40
  • 61
1

Basically %c refers to the character type specifier and *%c is used to exclude one character such that the character would be read from the console but it wouldn't be assigned to any variable. for eg. -:

suppose the input is 31/12/2018 and you want to output in the form of integers only and want to exclude '/' characters then you can use %*c here as - scanf("%d%*c%d%*c%d" , &day,&month,&year);

so this way you will exclude two '/' characters.

In similar manner %*d is used to exclude one integer, %*f to exclude one float , and %*s to exclude one word of the string. Hope it helped :)