This question already has an answer here:
#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 ...
If you give a space after your numbers,
scanf
must determine the end of the whitespaces to be matched: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):
If you call
scanf("%d")
, then after calling, the leftover stream is... 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 isYou see the whitespaces are gone immediately.
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.