无法计算文本文件中的字数

Trouble Counting No. of Words from Text File

C 语言、库 stdio.h、stdlib.h 和 string.h


问题

文本文件(text.txt)内容:

The price of sugar will be increased by RM 0.20 per kg soon. Please consume less sugar for a healthy lifestyle.

(注:文本文件末尾换行。)

题目要求我计算text.txt中字符、字母、元音、辅音、空格和单词的个数。

到目前为止,这是我的代码:

    FILE *t;
    t = fopen("text.txt", "r");
    int chrc = 0, ltrs = 0, vwls = 0, cnsnts = 0, blnks = 0, wrds = 0;
    char a[1], b[50];

    while (fscanf(t, "%c", &a[0]) != EOF) {
        chrc++;
        if (a[0] >= 65 && a[0] <= 90 || a[0] >= 97 && a[0] <= 122)
            ltrs++;
        if (a[0] == 'A' || a[0] == 'a' || a[0] == 'E' || a[0] == 'e' || a[0] == 'I' || a[0] == 'i' || a[0] == 'O' || a[0] == 'o' || a[0] == 'U' || a[0] == 'u')
            vwls++;
        cnsnts = ltrs - vwls;
        if (a[0] == 32)
            blnks++;
    }

    while (fscanf(t, "%s", &b) != EOF)
        wrds++;

    printf("Total number of characters: %d\n", chrc);
    printf("Number of letters: %d\n", ltrs);
    printf("Number of vowels: %d\n", vwls);
    printf("Number of consonants: %d\n", cnsnts);
    printf("Number of blanks (spaces): %d\n", blnks);
    printf("Approx no. of words: %d\n\n", wrds);
    fclose(t);

问题

当前的所有输出都符合预期,除了字数。我得到的不是预期的 21,而是:

Approx no. of words: 0

然后我编辑我的代码变成这样:

    FILE *t;
    t = fopen("text.txt", "r");
    int chrc = 0, ltrs = 0, vwls = 0, cnsnts = 0, blnks = 0, wrds = 0;
    char a[1], b[50];

    while (fscanf(t, "%s", &b) != EOF)
        wrds++;

    printf("Approx no. of words: %d\n\n", wrds);
    fclose(t);

我得到了预期的输出:

Approx no. of words: 21

我简单的删除了它上面的动作,结果输出变了。我真的不明白这是为什么。是因为我之前扫描过一次文本文件吗?

如何使第一个代码程序的字数输出为 21?我在这里做错了什么?

你错过了一个rewind可能是

rewind(t);
while (fscanf(t, "%s", &b) != EOF)
    wrds++;