Search code examples
cscanfwhitespaceformat-specifiersformat-string

Difference between "%d" and "%d " at scanf in C language


If I code like below

int main()
{
    int num;

    for(int i = 0; i < 3; i++)
    {
        printf("enter an integer\n");
        scanf("%d", &num);
        printf("%d\n", num);
    }
    return 0;
}

and then input "1 2 3", the output is

enter an integer
1 2 3
1
enter an integer
2
enter an integer
3

I know this is because buffer contains 1, 2, 3 at a time when input

however when I add space from "%d" to "%d " at scanf and input same thing "1 2 3" like before,

the output is

enter an integer
1 2 3
1
enter an integer
2
enter an integer

It didn't keep going like before with small change with "%d "

why does this happen?


Solution

  • Difference between “%d” and “%d ” at scanf in C language

    The difference is that when you use "%d " as format string, scanf()continues to consume white-space characters until it has encountered another non-white space character, like for example 2,3,4. A simply newline \n or another white space character after the input number won´t break the consuming.

    Whereas when you use "%d" only without white space after the format specifier, a white space character such as newline \n breaks the consuming.


    It didn't keep going like before with small change with "%d "

    Why does this happen?

    The reason is because scanf("%d ", &num); after it has consumed the 3 at the third walkthrough of the for-loop, still is consuming trailing white space until it has found another character.

    The 3 is not printed, because scanf()still is consuming. The whole program will get only finished if you enter another character like 4, in that specific case. This will work because the for-loop only has 3 walkthroughs of its body. If it would has more than this would even not work. You need to have one more character in stdin as you have walkthroughs of the for-loop with this kind of program.