Search code examples
cinputbufferscanfstdin

scanf format string not recognized


I' ve inserted the followings input for the follow program:

a b c d e

After the e letter I've pressed Enter, but the program blocks on scanf for i equal to 3. Seems that scanf is not able to fetch other character from stdin. Thanks in advance for your help.

    #include <stdio.h>
    #include <stdlib.h>

    int main()
    {
        char a[5];
        for (int i = 0; i < 5; i++)
        {
            scanf("%c ", a + i);
            printf("i = %d a[%d] = %c \n", i, i, a[i]);
        }

        int i = 0;
        while( i < 5 )
        {
            printf("%c ", a[i]);
            i++;
        }

        return 0;
    }

Solution

  • It doesn't block when i == 3 -- it completes that iteration -- it blocks when i == 4.

    That's because of the space after the %c in the scanf format -- a space causes scanf to read input and skip whitespace up until it finds a non-whitespace character. That non-whitespace character will then be left in the FILE input buffer as the next character to be read. So in the 5th iteration of the loop (i == 4), it reads the e then reads whitespace looking for non-whitespace. So the newline is skipped over (it's whitespace) and it starts (trying to) read the next line which blocks.

    Once you provide the next line (assuming its not empty/all whitespace), it will get a non-whitespace character and scanf will return.