I am a beginner in programming and I am learning C . I tried to read the contents from a file and do some processing on it .
The following is the program that I had written :
#include <stdio.h>
int main()
{
FILE *fp ;
int k = 0 ;
char c ;
while (c = getc(stdin))
{
if (c == 'a')
{
++k;
}
}
printf ("the value of k is %i" , &k) ;
}
And the file had input :
> hkjkjaaaaaaaaaak
>
> hjkjlkaaaaaaaaaghgh
>
> hjhkjklklklklklk
But I did not get any output in the console . I ran it on another online IDE and I got a run-time error saying "Time limit exceeded"
What can be the reason for the absence of output . Is it because I needed to somehow specify EOF character in the absence of which the program keeps running on and on?
After getting help from the answers I replaced the code with the following :
#include <stdio.h>
int main()
{
FILE *fp ;
int k = 0 ;
char c ;
while (c = getc(stdin) != EOF)
{
if (c == 'a')
{
++k;
}
}
printf ("the value of k is %i" , k) ;
}
This time the program ran and I got an output saying :
the value of k is 0.
Did it somehow reach EOF from the very beginning ?To verify this I tried comparing the character with 'h' and got the same output .
Is it because getc returns integer and this is not matching with any of the characters in the text ?
Thanks a lot for all the insights . The code worked at the end .Cheers