6-3 统计单词数量(文件)(*) (15分)

请编写函数,统计英文文章的单词数量。

函数原型

int CountWord(FILE *f);

说明:参数 f 为文件指针。函数值为该文件的单词数量。

裁判程序

#include 
#include 
#include 

int CountWord(FILE *f);

int main()
{
    FILE *f;
    int n;
    f = fopen("Story.txt", "r");
    if (!f)
    {
        puts("文件无法打开!");
        exit(1);
    }

    n = CountWord(f);

    if (fclose(f))
    {
        puts("文件无法关闭!");
        exit(1);
    }

    printf("单词数: %d\n", n);
    return 0;
}

/* 你提交的代码将被嵌在这里 */

打开 Windows 记事本软件,复制下面的文章内容,保存文件并命名为“Story.txt”。

Story.txt

A Cure for a Headache

One day a man went into a chemist's shop and said, "Have you anything to cure a
headache?"
The chemist took a bottle from a shelf,  held it under the gentleman's nose and
took out the cork.  The smell was so strong that tears came into the man's eyes
and ran down his cheeks.
"What did you do that for?"  he said angrily,  as soon as he could get back his
breath.
"But that medicine has cured your headache, hasn't it?" said the chemist.
"You fool," said the man, "It's my wife that has the headache, not me!"

样例输入

(无)

输出样例

单词数: 108

注:一串连续的字母被定义为一个单词。

int CountWord(FILE *f)
{
    char ch;
    int num=0,a=0;
    while((ch=fgetc(f))!=EOF)
    {
        //一串连续的字母被定义为一个单词。
        if((ch >='a' && ch <='z') || (ch >='A' && ch <='Z') )//是单词部分的时候
        {
            a=1;
        }
        if( ! ( (ch >='a' && ch <='z') || (ch >='A' && ch <='Z') ) && a==1 )//如果不是字母且第1次出现空格
        {
            a=0;//防止两个空格多次计数
            num++;
        }
        if( ! ( (ch >='a' && ch <='z') || (ch >='A' && ch <='Z') ) && a==0 )//如果不是字母且第2次及以上出现空格
        {
            continue;
        }
    }
    //注意返回值的情况!
    if(num!=0)
        return num;
    if(num==0 && a==1)//只有一个单词
        return 1;
    if(num==0 && a==0)//空文章
        return 0;
}

 

你可能感兴趣的:(c语言)