统计单词数量(文件)(*)

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

函数原型
int CountWord(FILE *f);
说明:参数 f 为文件指针。函数值为该文件的单词数量。

裁判程序

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

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) {
    int num=0,a=0;//num表示单词数量,a表示是否单词部分
    char ch;
    while((ch=fgetc(f))!=EOF) {
        if((ch >='a' && ch <='z') || (ch >='A' && ch <='Z')) { //字母部分 
            if(a==0) {//一个单词开始
                num++;
                a=1;
            }
        } else { //非字母部分 
            a=0; //一个单词结束
        }
    }
    return num;
}

由于是连续的字母定义为一个单词,就

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,151评论 0 10
  • 问题描述 Word Count 是一个著名的练手程序。一个文本文件包含若干行,每行包含若干个只包含小写字母的单词,...
    BitterOutsider阅读 5,585评论 0 0
  • Lesson 11excuse[ik'skju:z] v.原谅2me[mi:,mi] pron.我(宾格)3yes...
    造物家英语阅读 5,259评论 0 0
  • 久违的晴天,家长会。 家长大会开好到教室时,离放学已经没多少时间了。班主任说已经安排了三个家长分享经验。 放学铃声...
    飘雪儿5阅读 12,192评论 16 22
  • 今天感恩节哎,感谢一直在我身边的亲朋好友。感恩相遇!感恩不离不弃。 中午开了第一次的党会,身份的转变要...
    余生动听阅读 13,586评论 0 11