What is the effect of trailing white space in a scanf() format string?

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.


A white-space character (space, newline, horizontal and vertical tab) in a format string matches any number of white-space characters in the input.
In your first case

  scanf("%d  ",&j);

when it encounters the white-space char (WSC) ' ' then it will eat all the white spaces input by user including \n on pressing Enter and it will expect to enter a non-WSC . In this case your program will terminate by pressing Ctrl + Z.


A whitespace character in your scanf format matches any number of whitespace characters as described by isspace. So if you have tailing spaces, newlines, tabulators or any other whitespace character then it will also be consumed by scanf before it returns.