简体   繁体   中英

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

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 as scanf("%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 scanf s, it appears to be that both of

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

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM