linofex
linofex

Reputation: 340

difference in scanf parameters

When I write a program, I don't give attention about parameters of scanf. What is the difference between:

scanf("%d %d", &x,&y);

and

scanf("%d%d", &x,&y);

note the space between %ds. I tried on my pc, but I can't see the difference.

Also, what about %c instead of %d - what is the difference between

scanf("%c %c", &x,&y);

and

scanf("%c%c", &x,&y);

Can you give me useful examples to understand this stupid thing?

Upvotes: 2

Views: 106

Answers (3)

autistic
autistic

Reputation: 15642

A format directive that matches whitespace (e.g. anything for which isspace returns true) causes as much whitespace as possible to be read and discarded from the stream (stdin, in this case).

This process is required prior to the %d format directive translating digits, anyway; that is, the %d directive will read and discard as much whitespace as possible, and then read and translate a sign and/or sequence of decimal digits to an int.

In summary, with or without the whitespace directive, the functionality of these two statements is identical; the whitespace directive is superfluous in this case.

Upvotes: 1

Andreas DM
Andreas DM

Reputation: 10998

In your case they both result in the same whether you put a space between or not :)

From cppreference:

All conversion specifiers other than [, c, and n consume and discard all leading whitespace characters (determined as if by calling isspace) before attempting to parse the input. These consumed characters do not count towards the specified maximum field width.

The conversion specifiers that do not consume leading whitespace, such as %c, can be made to do so by using a whitespace character in the format string:

scanf("%d", &a);
scanf(" %c", &c); // ignore the endline after %d, then read a char

So your example: scanf("%c%c", &x, &y); will not skip whitespace.
If you input a b followed by enter it will read a and a whitespace.
On the other hand if you input ab it will read a and b as you wanted.

In the example: scanf("%c %c", &x, &y);, if you input a and hit enter, it will ignore the newline, and let you enter the other character.

Upvotes: 2

Shreevardhan
Shreevardhan

Reputation: 12641

scanf("%d %d", &x, &y) will eat the space (if any) after first integer is read and then read the second integer, while scanf("%d%d", &x, &y) will ignore whitespace while reading two integers. However both produce same results when run.

Upvotes: 1

Related Questions