I have this program that asks the user for an input string and two characters. One character to be replaced and the other that will replace the old one. I call a function named replace() that loops through the string, looking for the old character and replacing it with the new character. It prints the new string in main(), but it doesn't work right. What did I do wrong?
#include <stdio.h>
#include <string.h>
void replace(char string[], char old, char new);
int main()
{
char input[100], newChar, oldChar;
char newstr[100];
printf("Enter a string: ");
fgets(input, 100, stdin);
printf("Enter a character to replace: ");
scanf("%c", &oldChar);
printf("Replace character with?: ");
scanf("%c", &newChar);
getchar();
replace(input, oldChar, newChar);
printf("Result: %s\n", input);
}
void replace(char string[], char old, char new)
{
int length = strlen(string);
int i = 0;
for(i=0; i<length; i++)
{
if(string[i] == old)
{
string[i] = new;
}
}
}
scanf("%c", &oldChar);-->scanf("%c", &oldChar);getchar();scanf("%c", &newChar);-->scanf(" %c", &newChar);.