it works with gets but not with fgets?

102 Views Asked by At
#include <stdio.h>
int main(){
    char a[20],b[20];
    int i,c=0,m=0;
    
    fgets(a,20,stdin);
    fgets(b,20,stdin);
    while(a[c]!=0){
        c++;
    }
    for(i=0;i<c;i++)
    { 
        if(a[i]==b[i])
        m=m+1;
    }
    printf("%d",m);      
}

when i use fgets to input it doesn't work but if I use gets it works. here i am comparing elements of string and showing number of similar element. for eg input a: 1010101 b: 9898101 then it give 4 as output, but when I use gets it gives 3.

1

There are 1 best solutions below

0
Vlad from Moscow On

Opposite to the unsafe function gets (that is not supported by the C Standard) the function fgets can append the inputted string with the new line character '\n' if the array where characters are read has enough space. So if two strings obtained by calls of fgets have equal lengths and the new line character is stored in them then it will be count in your second for loop.

To remove the new line character '\n' from a string obtained by a call of fgets you can use for example the following approach

#include <string.h>

//...

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

In general your program is incorrect because the user can enter strings of different lengths.