What is the difference between %*c%c and %c as a format specifier to scanf?

元气小坏坏 提交于 2020-01-11 09:16:22

问题


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?


回答1:


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.




回答2:


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.




回答3:


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 :)



来源:https://stackoverflow.com/questions/11109750/what-is-the-difference-between-cc-and-c-as-a-format-specifier-to-scanf

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