Create a C function, which searches how many times a letter appears in a string

Asked

Viewed 45 times

-2

I need to make this function count how many times a letter has been said in the string. However, the result always returns 0.

#include <stdio.h>
#include <string.h>

void contador(char palavra[], char letra[], int aux){
    int qntd, i;

    qntd = strlen(palavra);
    for(i = 0; i < qntd; i++){
        if(palavra[i] == letra){
        aux++;
        }
    }
}

int main(){
    char palavra[50], letra[1], aux;

    printf("Digite um palavra: \n");
    scanf(" %s", &palavra);

    printf("Digite um letra a ser encontrada: \n");
    scanf(" %s", &letra);

    contador(palavra, letra, aux);
    printf("O numero de vezes que a letra %s apareceu, foi de: %d", letra, aux);
}

1 answer

0

You are not going to variable aux by reference, so the value is not updated in main.

void contador(char palavra[], char letra[], int *aux){

..

contador(palavra, letra, &aux);

considering the comment, the variable aux is the type char. Change to int that should work:

#include <stdio.h>
#include <string.h>

void contador(char palavra[], char letra[], int *aux){
    int qntd, i;

    qntd = strlen(palavra);
    for(i = 0; i < qntd; i++){
        if(palavra[i] == letra){
        aux++;
        }
    }
}

int main(){
    char palavra[50], letra[1];
    int aux = 0; //detalhe: inicialize sempre a variável do contador.

    printf("Digite um palavra: \n");
    scanf(" %s", &palavra);

    printf("Digite um letra a ser encontrada: \n");
    scanf(" %s", &letra);

    contador(palavra, letra, &aux);
    printf("O numero de vezes que a letra %s apareceu, foi de: %d", letra, aux);
}
  • Now he’s even returning values, but random values...

  • ? ??@V
  • 3

    Since now on contador, aux is a pointer to int, you forgot to change the aux++. Fixing this will probably work. Anyway, I don’t like this idea of passing the variable aux by reference, as the function of the contador is to count the amount of times a letter occurs in a string, that amount should be its return value and not one of its arguments.

  • 2

    There’s another mistake in palavra[i] == letra, for letra[] was declared as an array in the function signature contador and what’s worse in function main also. Well, in main, scanf is at least writing two characters in a declared array to fit only one, in contador, if one insists on using an array, the comparison should be palavra[i] == letra[0].

Browser other questions tagged

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