0
I’m trying to create a code in which I have to count the number of times a word appears within a sentence, but after a lot of searching and searching about, I can only find codes that use the fgets function, I was wondering if you would know why else, I could replace the fgets and still run the whole. That’s the code I’ve developed for now :
#include <stdio.h>
int main()
{
char frase[250];
char palavra[50];
int i;
int j = 0;
int count = 0;
printf( "escveva uma frase: " );
scanf( "%[^\n]", frase );
printf( "escreve uma palavra: " );
scanf( "%s", palavra );
for(int i = 0; frase[i] != '\0'; i++)
if (palavra[j] == frase[i])
{
j += 1;
if (palavra[j] == '\0')
{
count += 1;
j == 0;
}
}
else
{
j = 0;
}
printf( "count = %d\n", count);
return 0;
}
On top of everything else, I believe I’m doing something wrong on the go or on the other side, because I’m not getting the result I wanted, but I can’t understand where I might be going wrong. If you can help me understand my mistake, and what else besides fgets could be used, I would be very grateful. Besides, I believe I have to put some strings, like strlen, but I only learned to use them with characters
Several wrong things. It starts with confusion between the assignment operator
=
and the comparison operator for equality==
. Do not use the&
in the scanf function for string reading.– anonimo
Thank you, now I did!! I didn’t understand the reason for the mistake, and now it worked
– Alexandre lopez