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

时光毁灭记忆、已成空白 提交于 2019-11-29 16:03:26

问题


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?


回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/34874347/what-does-an-asterisk-in-a-scanf-format-specifier-mean

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