What is difference between scanf("%d")
and scanf("%d ")
in this code, where the difference is the trailing blank in the format string?
#include <stdio.h>
int main(void)
{
int i, j;
printf("enter a value for j ");
scanf("%d ",&j);
printf("j is %d\n", j);
printf("enter a value for i ");
scanf("%d", &i);
printf("i is %d\n", i);
return 0;
}
How does the scanf()
function actually work when I add spaces after the format specifier like scanf("%d ", &j);
?
A whitespace character in a scanf format causes it to explicitly read and ignore as many whitespace characters as it can. So with scanf("%d ", ...
, after reading a number, it will continue to read characters, discarding all whitespace until it sees a non-whitespace character on the input. That non-whitespace character will be left as the next character to be read by an input function.
With your code:
printf("enter a value for j ");
scanf("%d ",&j);
printf("j is %d \n", j);
it will print the first line and then wait for you to enter a number, and then continue to wait for something after the number. So if you just type 5Enter, it will appear to hang — you need to type in another line with some non-whitespace character on it to continue. If you then type 6Enter, that will become the value for i
, so your screen will look something like:
enter a value for j 5
6
j is 5
enter a value for i i is 6
Also, since most scanf %-conversions also skip leading whitespace (all except for %c
, %[
and %n
), spaces before %-conversions are irrelevant ("%d"
and " %d"
will act identically). So for the most part, you should avoid spaces in scanf conversions unless you know you specifically need them for their peculiar effect.