#include<stdio.h>
#include<conio.h>
int main() //main returns an int
{
int i;
char a,b,str[100];
printf("Enter the string\n");
fgets(str,sizeof(str),stdin);//gets is dangerous
printf("Enter the character to be replaced\n");
scanf(" %c",&a); //space before %c is not neccessary here
printf("Enter the character to replace\n");
scanf(" %c",&b); //space before %c is compulsory here
for(i=0;str[i]!='\0';i++)
{
if(str[i]==a)
{
str[i] = b;
}
//else //This part is not neccessary
//continue;
}
printf("The new string is ");
puts(str);
return 0; //main returns an int
}
I've used fgets
because gets
is dangerous as it does not prevent buffer overflows.
The space before %c
in the scanf
is to skip blanks,i.e,spaces,new-lines etc and it isn't needed in the first scanf
is that fgets
also consumes the new-line characters and puts it into the buffer.
The reason that the else continue;
isn't needed is that the loop is going to check the condition as it has reached the end of the loop body.
I've used int main()
and return 0
because as per the latest standards,it should
Finally,you have an unused header conio.h
in your program.