2

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;
        }
    }
}
6
  • 2
    scanf("%c", &oldChar); --> scanf("%c", &oldChar);getchar(); Commented Sep 27, 2015 at 6:38
  • Wooaahh. Tried it out. It worked. Thanks :D Commented Sep 27, 2015 at 6:40
  • 2
    Or scanf("%c", &newChar); --> scanf(" %c", &newChar);. Commented Sep 27, 2015 at 6:44
  • 1
    Note that one of the most basic debugging techniques is "print the inputs to ensure you got what you expected". If you had printed the characters, you would have seen the trouble. Commented Sep 27, 2015 at 7:43
  • @CoolGuy How do you replace with the space ? Commented Sep 28, 2015 at 0:51

1 Answer 1

1

Please try this, I think a getchar is missing:

printf("Enter a character to replace: ");
scanf("%c", &oldChar);
getchar();

printf("Replace character with?: ");
scanf("%c", &newChar);
getchar();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.