For starters these variables
char *str1 , *str2 ;
are not initialized. So the program already has undefined behavior. You need to declare character arrays like for example
enum { N = 20 };
char str1[N], str2[N];
The standard function fgets
can append the new line character '\n'
to the entered string provided that there is enough space in the character array.
You should remove this character. For example
fgets(str1, 20, stdin);
fgets(str2, 20, stdin);
str1[ strcspn( str1, "\n" ) ] = '\0';
str2[ strcspn( str2, "\n" ) ] = '\0';
The function lencompare
should be declared and defined like
int lencompare( const char *str1, const char *str2 )
{
return strlen( str1 ) == strlen( str2 );
}
The function compare
has undefined behavior because in some paths of execution it returns nothing.
Also it should be declared like
int compare( const char *str1, const char *str2 );
Within the function you two times call the function lencompare
:
if(lencompare(str1, str2)==1){
and
if(lencompare(str1, str2) == 0){
The program can look the following way
#include <stdio.h>
#include <string.h>
int lencompare( const char *str1, const char *str2 )
{
return strlen( str1 ) == strlen( str2 );
}
int compare( const char *str1, const char *str2 )
{
int equal = lencompare( str1, str2 );
if ( equal )
{
while ( *str1 == *str2 && *str1 )
{
++str1;
++str2;
}
equal = *str1 == *str2;
}
return equal;
}
int main(void)
{
enum { N = 20 };
char str1[N], str2[N];
fgets( str1, sizeof( str1 ), stdin );
fgets( str2, sizeof( str2 ), stdin );
str1[ strcspn( str1, "\n" ) ] = '\0';
str2[ strcspn( str2, "\n" ) ] = '\0';
if ( compare( str1, str2 ) )
{
puts( "both length and content are same" );
}
return 0;
}
Its output might look like
Sridhar
Sridhar
both length and content are same
Pay attention to that instead of the while loop in the function compare
you could use the standard C function strcmp
. In this case the function compare will be very simple
int compare( const char *str1, const char *str2 )
{
return strcmp( str1, str2 ) == 0;
}
In fact there is no need to compare preliminary the lengths of the strings.