Search code examples
cstringloopsfor-loopfgets

How to use fgets in a loop?


I want to use a loop here. But my second fgets dont work properly!
In 1st loop it was okay! but after that it skips its second fgets!
How to fix it?
Thanks

#include<stdio.h>
#include<string.h>
int main (void)
{
char first_line[1000];
char second_line[2];
int i,n,j,k;
int count=0,flag=0;
scanf("%d ",&k);
for(int m=0; m<k; m++)
{
    fgets(first_line, 1000, stdin);
    fgets(second_line, 2, stdin);
    for(i=0; i<strlen(first_line); i++)
    {
        if(second_line[0]==first_line[i])
        {
            flag=1;
            count++;
        }
    }
    first_line[strlen(first_line)-1] = '\0';
    if(flag==1)
        printf("Occurrence of '%c' in %s = %d",second_line[0],first_line,count);

    else
        printf("%c isn't present",second_line[0]);
    count=0;
    flag=0;
}

return 0;
}

Solution

  • The problem is that the array second_line is declared as having only two elements.

    char second_line[2];
    

    Thus after this call

    fgets(second_line, 2, stdin);
    

    it can not accommodate the new line character that will be still in the input buffer. And the first call of fgets reads an empty string due to the presence of the new line character in the input buffer.

    At least you should Write

    char second_line[3];
    
    //...
    
    fgets(second_line, sizeof( second_line ), stdin);
    

    Take into account that in general this approach to remove the new line character from a string is wrong

    first_line[strlen(first_line)-1] = '\0';
    

    because it is not necessary that the string indeed contains a new line character.

    Instead write

    first_line[ strcspn( first_line, "\n" ) ] = '\0';