Why do interleaved scanf() + printf() statements r

2020-04-14 11:54发布

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);

标签: c printf scanf
2条回答
兄弟一词,经得起流年.
2楼-- · 2020-04-14 12:13

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 as scanf(" %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.

Why do interleaved scanf() + printf() statements result in both scanf() calls executing first, then both printf() calls?

I am assuming the input for n is 15. When you press Enter key then the \n character goes with 15 in the input buffer. scanf("%d\n",&n); reads the 15 and then skips \n. Now this scanf waits for a non-white-space character to be entered (unlike what you supposed that 15 should be printed) . When you enter a, it puts it back for the next call of scanf. The next statement scanf("\n%c",&ch); reads this a from the buffer and do not let the user to input the value for ch. Since the value of n and ch both is now read by these scanfs, it appears to be that both of

printf("d-%d \n",n);
printf("ch-%d \n",ch);   

executes after both of the scanfs call (which is not the case!).

查看更多
该账号已被封号
3楼-- · 2020-04-14 12:18

Any whitespace in a scanf format is like any other whitespace in a scanf format. It simply tells scanf 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.

查看更多
登录 后发表回答