问题
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