How do I do a C function that removes a character typed by the user from the phrase he typed? Unable to do the function

Asked

Viewed 18 times

1

//Ex: if the user type 'hello world' and type 'o' then the program must return the Mund, removing the letter the user typed.

#include <stdio.h>
#include <string.h>
int main(){
    char str[20],ch;
    int i, n, j;
    printf("Digite uma frase:\n");
    scanf("%s",str);
    printf("Digite uma letra dessa frase:\n");
    scanf("%c",&ch);
    n=strlen(str);

    for(i=0, j=0; i<n; i++)
    {
        if(str[i]!=ch)
        {
            str[j]=str[i];
            j++;
        }
    }
    str[j]='\0';
    printf("removemos a letra digitada: %s\n", str);
    return 0;
}
  • The way you did, using scanf("%s",str);, will only be able to read a single word, because the space is considered a delimiter by the scanf function and stops reading. Try scanf("%[^\n]",str);, read until you find a line end character (' n').

  • Another problem that may occur is that your reading of the letter to be removed may pick up something from the input buffer other than the letter you reported. Eliminating these problems your code runs correctly. See: https://ideone.com/VOgx6r

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.