Why does this cycle only run 4 times?

I am starting to program c. I just want to know why this loop is not working correctly.

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

int main()
{
    int i;
    char x[8];
    char t;

    for (i = 0; i < 8; i++) {
        scanf("%c", &t);
        x[i] = t;
    }
    return 0;
}

      

+3


source to share


2 answers


Because when any input is entered from the keyboard, we need to hit enter to confirm the completion of the input. This enter stays in the buffer and if the next input is a char or string, stores enter a string or char var and do not wait for that char or string to be input. In this case, the first input given on execution stores char in X [0] and enters x [1], and so on. So the loop is executed 8 times, but it seems 4 times because it only asks for input four times. To test to put one printf in a loop



+3


source


runs 8 times. Whenever you hit enter to submit, you are typing a space character, which consumes one of your loop iterations.



+1


source







All Articles