-1
Good afternoon,
My goal is to insert a string of up to 500 characters, and then read a letter. Creating, for this purpose a function that counts how many times that letter appears in the text.
The problem is that I must pass the text by reference to the function and I do not know if it is working. The function should receive the text, the letter and return the number of repetitions of the letter.
#include <stdio.h>
#include <stdlib.h>
int contagem(char *txt, char letra)
{
int contagem=0;
int i;
for (i=0; txt[i] !='\0';i++)
{
if (txt[i]==letra)
contagem++;
}
return contagem;
}
int main()
{
char txt[501],letra;
printf("Insira o texto:");
scanf("%s", txt);
printf("Deseja contar ocorrencia de qual letra?");
scanf(" %c", letra);
printf("O caracter aparece %d vezes \n", contagem(*txt,letra));
}
Here:
scanf(" %c", letra);
lacked the&
:scanf(" %c", &letra);
. Here:contagem(*txt,letra)
the correct is:contagem(txt, letra)
.– anonimo
I made this correction, however, after inserting the string and the letter I want to search, the command prompt freezes and closes.
– Gustavo Scholze
Differentiate the variable name used to count from the function name. If your string has space characters, replace
%s
for[^\n]
, otherwise the program will close the reading on the first space. See working on: https://ideone.com/Psm2UM– anonimo