Frequency function in C

I wrote a program that should take a string and a letter, and then call a function that has two parameters (string, letter), and then count the frequency of the letter in the string.

The problem with my code is that it always returns numwith a zero value for any letter.

#include <stdio.h>
#include <stdlib.h>

int Occur(char [], char);

int main()
{
    char s[100], l;
    printf("Enter A String:\n");
    scanf("%s",s);
    printf("Enter A Letter:\n");
    scanf("%c",&l);
    getchar();

    printf("Num Of Occurance is %d ",Occur(s,l));

    return 0;
}

int Occur(char S[100], char L)
{
    int i;
    int num=0;

    for(i=0; S[i]!='\0'; i++)
    {
        if(S[i]==L)
        num++;
    }

    return num;
}
+6
source share
4 answers

The cause of the problem:

scanf("%c",&l) //Here %c takes enter key of scanf("%s",s);;

So, in your problem there are mainly 2 solutions:

Sol. 1 =>scanf(" %c",&l) //use whitespace before %c

Sol. 2 => Use fflush (stdin), which flushes the stream's output buffer.

int main()
{

char s[100],l;
printf("Enter A String:\n");
scanf("%s",s);
printf("Enter A Letter:\n");
fflush(stdin);                       //here fflush(stdin) used to flushes the output buffer.
scanf("%c",&l);
l = getchar();
......
......
}

NOte: Since fflush (stdin) has undefined behavior, so always use priority for solution 1 instead of fflush (). :)

+4

. , , , L, , L .

-, , L - , scanf... scanf (" %c") [ ] .

, , fflush(). , , getchar() scanf("%s") scanf("%c"). , scanf(" %c");

, , , char ( \n) , , %c char >

+5

.

int Occur(char S[100], char L)

int Occur(char S[] , char L)

100 .

, , . Stdin , , juggad scanf getchar() .

0

. char getchar scanf. l = getchar() ( scanf ).

#include <stdio.h>
#include <stdlib.h>

int Occur(char [],char);


int main()
{

char s[100],l;
printf("Enter A String:\n");
scanf("%s",s);
printf("Enter A Letter:\n");
scanf("%c",&l);
l = getchar();

printf("Num Of Occurance is %d ",Occur(s,l));


return 0;
}


int Occur(char S[100],char L){

int i;
int num=0;

for(i=0;S[i]!='\0';i++){

if(S[i]==L)
    num++;
}

return num;

}
0

Source: https://habr.com/ru/post/1017249/


All Articles