What does an asterisk in a scanf format specifier mean? [duplicate]

喜你入骨 提交于 2019-11-30 10:52:40

*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.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!