Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 484
ild0tt0re Avatar asked Jun 19 '12 21:06

ild0tt0re


People also ask

What is the difference between scanf %C and scanf %C?

Solution 1. The difference is that scanf uses the format string literally: the need for a space implies that your input is not '+' but has whitespace before it. "%c" is a scanf "special" code: it does not skip whitespace characters at all (unlike "%d" which does).

What is difference between %C and %S in c?

%c is the format specifier for character and %s is the format specifier for string(character array).

What does %C do in scanf?

A simple type specifier consists of a percent (%) symbol and an alpha character that indicates the type. Below are a few examples of the type specifiers recognized by scanf: %c — Character. %d — Signed integer.

What is the difference between %D and %C in c?

They are string format specifiers. Basically, %d is for integers, %f for floats, %c for chars and %s for strings.


2 Answers

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.

like image 197
ouah Avatar answered Nov 10 '22 06:11

ouah


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.

like image 40
Nick Avatar answered Nov 10 '22 06:11

Nick