white space in format string of scanf() [duplicate

2019-07-29 06:47发布

问题:

This question already has an answer here:

  • using scanf(“%d ”) with a space after the %d 1 answer
#include<stdio.h>
int main() {
    int a,b;
    printf("Enter values of a and b\n");
    scanf(" %d%d ",&a,&b);
    printf("a=%d b=%d", a, b);
    return 0 ;
}

Here if I use scanf(), as in my code then the compiler expects the user to enter three values, I am unable to understand this , when i use scanf() without any white space then it asks for only two inputs as expected , so i am confused whats the difference between these two , plz explain ...

回答1:

If you give a space after your numbers, scanf must determine the end of the whitespaces to be matched:

scanf("%d ", &a);

Here the space means read and discard all whitespaces. A non-whitespace character (or EOF) must appear for scanf to make it clear what all is so they can be properly read and discarded.

Consider this input stream (dots are character indicators):

   1   2
........

If you call scanf("%d"), then after calling, the leftover stream is

   2
....

... where the whitespaces will be discarded at next read. Note the leading spaces are automatically discarded when reading the number.

If you call scanf("%d ") instead, the leftover stream is

2
.

You see the whitespaces are gone immediately.



回答2:

Take a look at this.

You can use a space between the %d's. That will require from the user to input something like: 12 32 (with the spaces).

If you don't want that, you should use a loop with the scanf.

Good luck.