6-4 统计单词数量(文件)(*) (10 分)

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

函数原型

 

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 i,sum=0,b=0;
    char a;
    while((a=fgetc(f))!=EOF)
    {
        if(((a>='a'&&a<='z')||(a<='Z'&&a>='A'))&&b==0)//遇到字母情况继续循环
        {
            b=1;
            continue;
        }
        else if((!((a>='a'&&a<='z')||(a<='Z'&&a>='A')))&&b==1)//非字母情况
        {
            b=0;
            sum++;
        }
    }
        if(b==1)//b作为判断返回值条件
        return sum+1;//一个字母的情况
        else
        return sum;
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

行人 成双

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值