The below code produces a ridiculous output of 32674 for a test input of counting number of 'aa' in 'aaa'. How do i go about correcting this?
#include<stdio.h>
#include<string.h>
int main()
{
int i,j,len ,k ,count, num ;
char str[100],sub[100],comp[100] ;
// sub is the sub string .
printf("Please enter the string") ;
fgets(str,sizeof(str),stdin) ;
printf("Enter the substring to be searched for") ;
fgets(sub,sizeof(str),stdin) ;
len=strlen(sub) ;
for ( i=0 ; i < (strlen(str) - len ); i++ )
/*Goes till length of string - length of sub string so that all
characters can be compared. */
{
num = i + len ;
for ( j=i,k=0 ; j<num ; j++, k++ )
//Loop to store each sub string in an array comp.
{
comp[k]=str[j] ;
}
comp[k+1]='\0' ;
/*A previous suggestion given : comp[k]
to be the null character but I dont see how/why? and that is
giving a similarly wrong output as well. */
if ( strcmp(comp,sub) == 0 )
{ count++ ; }
}
printf("no of occurances is:%d",count) ;
return 0 ;
}