1

This is the first code:

int a, b;
scanf("%d%*c%d",&a,&b);
printf("%d %d",a,b);

if I input

4
5

it prints

4 5

This is the second code:

int a,b;

scanf("%d %*c %d",&a,&b);

printf("%d %d",a,b);

if is input

4
5
6

it prints

4 6

why %*c skips a character only if it is surrounded by a white space

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
  • What EXACTLY did you input? Did it actually contain commas? – Scott Hunter Jan 11 '14 at 11:30
  • no it didn't contained the commas –  Jan 11 '14 at 11:31
  • 6
    I think that a comment saying that [your question](http://stackoverflow.com/q/21061400/771663) is off-topic is not an encouragement to repost the same question again and again... – Massimiliano Jan 11 '14 at 11:33
  • Read [scanf Format Specification Syntax](http://wpollock.com/CPlus/PrintfRef.htm) : `*` == `Assignment Supression. This modifier causes the corresponding input to be matched and converted, but not assigned (no matching argument is needed).` – Grijesh Chauhan Jan 11 '14 at 11:34
  • but Grijesh I want to know why white space is needed around %*c –  Jan 11 '14 at 11:36
  • @user3180902 from [scanf manual](http://man7.org/linux/man-pages/man3/scanf.3.html) Because `A sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). This directive matches any amount of white space, including none, in the input.` and `%*c` will not skips white spaces – Grijesh Chauhan Jan 11 '14 at 11:38

2 Answers2

1

You are not inputting quite what you think you are: think that the two input sequences are 4 then 5 and 4 then 5 then 6 - what you are inputting is 4 newline 5 and 4 newline 5 newline 6 - the spaces in your scanf can match spaces or newlines.

Note that you should also test with:

4 5
4,5
4?5
4 5 6
4,5,6

etc.

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
1

Q: Why use white-space around "%*c"?

A: The white-space in " %*c" is a scanf() directive that skips white-spaces (0 or more) during the scan thus preventing "%*c" from itself reading a white-space. Without the leading white-space, "%*c" will scan any 1 char, white-space or not. The trailing white-space in "%*c " has no effect at all on what "%*c" already did. The trailing white-space directive simple skips subsequent white-spaces.


White-space in a format is not needed around "%*c", it depends on the coding goal.

Most specifiers, like "%d", "%f", "%s" skip leading white-spaces. (White-space being ' ', '\n', '\t', etc. see isspace()).

Simply having a format directive " " or "\n" also skips white-spaces.

3 specifiers "%c", "%n" and "%[scanset]" do not skip leading white-spaces.

Since many programmers want scanf() to skip leading white-spaces before a "%c" a preceding white-space is needed as in " %c".

Note: "%d %*c %d" will scan the same as "%d %*c%d".

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256