Using fgets in a loop to read from terminal

717 Views Asked by At

I'm trying to read from terminal a few lines of text with fgets. The problem is it only read one line and stops. I tried flushing buffer and using getchar to absorb the newline but it still didn't work.

#include <stdio.h>

int main()
{
        int count = 2;
        int len = 5;
        char str[count][len];

        for(int i = 0; i < count; i++)
        {
                fgets(str[i], len, stdin);
                fflush(stdin);
        }
}
1

There are 1 best solutions below

4
On BEST ANSWER

fflush(stdin); is undefined behaviour. Don't use it.

I think, your problem is that you are inputting the more len characters and thus the second call to fgets() reads in the character left by the first call. Just increase len sufficiently.

You should also check the return value of fgets() for failure.