计算C中每一行上单词“ Hello”的出现

我正在尝试编写一个计算每行中“ Hello”发生次数的程序

#include <stdio.h>
#include <string.h>
#define FALSE 0
#define TRUE 1

unsigned countWords(char *str) 
{ 
    int state = FALSE; 
    unsigned wc = 0;   

    while (*str) 
    { 
        if (*str == ' ' || *str == '\n' || *str == '\t') 
            state = FALSE; 

        else if (state == FALSE) 
        { 
            state = TRUE; 
            ++wc; 
        } 
        ++str; 
    } 

    return wc; 
} 

int main()
{
    char a[1000];
    int nwords = 0;
    int count = 0;
    while(fgets(a, sizeof(a), stdin))
    {
        nwords = countWords(a);
        fseek(stdin,0,SEEK_SET);
        for(int i = 0; i < nwords; i++) 
            for(;scanf("%s", a)!=EOF;)
                if(!strcmp(a, "Hello")) count++;
        printf("%d\n", count); 
        count = 0;
        nwords = 0;
    }
    return 0;
} 

对于这样的输入:

Hello Hello
is Hello here
no it is not here

输出应为:

2
1
0

but my output is just 3. Why does this happen when I set count = 0 after printf? I guess when it prints it is already 3. If I put printf inside a for loop it doesn't work either. Isn't while(fgets.....) supposed to read a line, do the stuff inside the loop until the end of line is reached and then go to another line and so on?

评论