【问题标题】:Trouble Counting No. of Words from Text File无法计算文本文件中的字数
【发布时间】:2017-11-11 06:47:10
【问题描述】:

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

我只是删除了上面的操作,输出改变了。我真的不明白为什么会这样。是因为我之前对文本文件进行了一次 fscanf 处理吗?

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

【问题讨论】:

标签: c text-files std stdio


【解决方案1】:

你可能错过了rewind

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    相关资源
    最近更新 更多