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);
}
}
fflush(stdin);is undefined behaviour. Don't use it.I think, your problem is that you are inputting the more
lencharacters and thus the second call tofgets()reads in the character left by the first call. Just increaselensufficiently.You should also check the return value of
fgets()for failure.