the following c programming code gives a core dump segmentation fault , please tell me why i am getting this error and help me by giving a corrected version of this code .Thank you!
#include <stdio.h>
#include <string.h>
int main()
{
char str[100], ch;
int i, Flag;
Flag = 0;
printf("\n Please Enter any String : ");
fgets(str,sizeof(str),stdin);
printf("%s",str);
printf("\n Please Enter the Character that you want to replace with : ");
scanf("%c", &ch);
for(i = 0; i <= strlen(str); i++)
{
str[i]=ch;
}
str[i]='\0';
printf("\n The characters have been found and replaced with %c and they occur %d times ", ch, i + 1);
printf("The replaced string is %s ",str);
return 0;
}
Try this.
#include <stdio.h>
#include <string.h>
int main()
{
char str[100], ch;
int i, Flag;
Flag = 0;
printf("\n Please Enter any String : ");
fgets(str,sizeof(str),stdin);
printf("%s",str);
printf("\n Please Enter the Character that you want to replace with : ");
scanf("%c", &ch);
for(i = 0; i < strlen(str); i++) //change <= to <
{
str[i]=ch;
}
str[i]='\0';
printf("\n The characters have been found and replaced with %c and they occur %d times ", ch, i + 1);
//printf("The replaced string is %s ",str);
return 0;
}