What is the difference between %*c

2019-02-24 18:27发布

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?

2条回答
我想做一个坏孩纸
2楼-- · 2019-02-24 18:58

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.

查看更多
倾城 Initia
3楼-- · 2019-02-24 19:01

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.

查看更多
登录 后发表回答