Can you please explain one thing in the following code:
#include<stdio.h>
int main()
{
int n;char ch,ch1;
scanf("%d\n",&n);
printf("d-%d \n",n);
scanf("\n%c",&ch);
printf("ch-%d \n",ch);
scanf("\n%c",&ch1);
printf("ch1-%d \n",ch1);
printf("%d %d %d\n",n,ch,ch1);
return 0;
}
Why is it that after entering the value of n,it directly asks for the value of ch and then directly executes the statements to print their respective values ie the statements:
printf("d-%d \n",n);
printf("ch-%d \n",ch);
scanf("%d\n",&n);
skips any number of trailing white-spaces (including none) after actual the input. It can also be written asscanf("%d ",&n);
.scanf("\n%c",&ch);
skips any number of leading white-spaces (including none) before the actual input. It can also be written asscanf(" %c",&ch);
.NOTE: A white-space in a format specifier is able to skip any number of white-spaces.
Now what does it mean by skipping white-spaces ?
It means
scanf
repeatedly reads white-space characters from input until it reaches a non-white-space character. Now there is no white-space characters left in the buffer.When it encounters a non-white-space character, then this character is put back to be read again during the scanning of the next input item or during the next call of
scanf
.Now coming to your question.
I am assuming the input for
n
is15
. When you press Enter key then the\n
character goes with15
in the input buffer.scanf("%d\n",&n);
reads the15
and then skips\n
. Now thisscanf
waits for a non-white-space character to be entered (unlike what you supposed that15
should be printed) . When you entera
, it puts it back for the next call ofscanf
. The next statementscanf("\n%c",&ch);
reads thisa
from the buffer and do not let the user to input the value forch
. Since the value ofn
andch
both is now read by thesescanf
s, it appears to be that both ofexecutes after both of the
scanf
s call (which is not the case!).Any whitespace in a
scanf
format is like any other whitespace in ascanf
format. It simply tellsscanf
to skip any whitespace in the input.Most format codes doesn't need it though as they skip leading whitespace automatically, but one that does (unless you want to actually read a whitespace character) is the
"%c"
format code.You might also want to read this reference.