31

So I stumbled across this code and I haven't been able to figure out what the purpose of it is, or how it works:

int word_count;
scanf("%d%*c", &word_count);

My first thought was that %*d was referencing a char pointer or disallowing word_count from taking char variables.

Can someone please shed some light on this?

Greg Bacon
  • 134,834
  • 32
  • 188
  • 245
Joel
  • 5,732
  • 4
  • 37
  • 65
  • 9
    See: [The difference between %*c%c and %c](http://stackoverflow.com/questions/11109750/the-difference-between-cc-and-c) – P.P Jan 19 '16 at 10:38
  • 1
    [**fscanf documentation**](http://en.cppreference.com/w/c/io/fscanf). – edmz Jan 19 '16 at 18:02

3 Answers3

32

*c means, that a char will be read but won't be assigned, for example for the input "30a" it will assign 30 to word_count, but 'a' will be ignored.

Viktor Simkó
  • 2,607
  • 16
  • 22
23

The * in "%*c" stands for assignment-suppressing character *: If this option is present, the function does not assign the result of the conversion to any receiving argument.1 So the character will be read but not assigned to any variable.


Footnotes:

1. fscanf

BeyelerStudios
  • 4,243
  • 19
  • 38
15

To quote the C11 standard, chapter §7.21.6.2, fscanf()

[...] Each conversion specification is introduced by the character %. After the %, the following appear in sequence:

— An optional assignment-suppressing character *.
— [...]
— A conversion specifier character

and regarding the behavior,

[..] 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. [...]

That means, in case of a format specifier like "%*c", a char will be read from the stdin but the scanned value won't get stored or assigned to anything. So, you don't need to supply a corresponding parameter.

So, in this case,

scanf("%d%*c", &word_count);

is a perfectly valid statement.

For example, What it does in a *nix environment is to clear the input buffer from the newline which is stored due to pressing ENTER key after the input.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261