im a beginner to C,, and i was writing a code to print a square of a user entered character.
usually when we need to input two integers (say x and y) using scanf()
we write this scanf("%d%d", &x, &y)
but according to the needs of my code i am supposed to input one integer (say m) and a character (say ch).
I wrote it as scanf("%d%c", &x, &ch)
but it has an error, when i execute the program it only asks the integral value to be entered and then it just stop executing.
I searched for this and i found that i need to put space between %d
and %c
as scanf("%d %c", &x, &ch);
Can anyone explain this why we need to put space between this?
Meaning of whitespace characters in the format string (from http://www.cplusplus.com/reference/cstdio/scanf/?kw=scanf):
Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).
When your code is:
scanf("%d%c", &x, &ch)
and you enter
10
in your console:
10
is read and stored in x
.ch
.If you use
scanf("%d %c", &x, &ch)
and you enter
10
10
is read and stored in x
.ch
. This is because stdin
is typically line buffered.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With