I wrote a program that should take a string and a letter, then call a function which have two parameters (the string, the letter) and then count frequency of letter in the string.
The problem with my code is that it always returns num
with value zero 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;
}
First, you should have tried debugging your code. If you would have done it, you would have seen that the letter you thought L holds is not what L actually holds.
Second, your problem is simple, L is not getting the letter you enter because of the enter from the string before is stuck in the scanf buffer... use scanf (" %c")
[with preceeding whitespace] to resolve.
As mentioned in other answers, there are other solutions like the unrecommended fflush()
. An alternative that is not considered harmful is getchar()
between the scanf("%s")
and the scanf("%c")
. That will give you the same effect as using scanf(" %c");
The reason that all of these methods work is because they all consume the last char
(which is, in your case the \n
) stuck in the buffer, and thus allowing the %c
to consume the char
you actually intend to read
Reason of problem :
scanf("%c",&l) //Here %c takes enter key of scanf("%s",s);
;
So, there are mainly 2 solution to your problem:
Sol. 1 => scanf(" %c",&l) //use whitespace before %c
Sol. 2 => Use fflush(stdin) that flushes the output buffer of a stream.
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 to Solution 1 , instead of fflush(). :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With