請編寫函數(shù)展姐,統(tǒng)計英文文章的單詞數(shù)量躬存。
函數(shù)原型
int CountWord(FILE *f);
說明:參數(shù) f 為文件指針。函數(shù)值為該文件的單詞數(shù)量孝扛。
裁判程序
#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("文件無法關(guān)閉!");
exit(1);
}
printf("單詞數(shù): %d\n", n);
return 0;
}
/* 你提交的代碼將被嵌在這里 */
打開 Windows 記事本軟件,復(fù)制下面的文章內(nèi)容幽崩,保存文件并命名為“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!"
樣例輸入
(無)
輸出樣例
單詞數(shù): 108
注:一串連續(xù)的字母被定義為一個單詞。
int CountWord(FILE *f) {
int num=0,a=0;//num表示單詞數(shù)量慌申,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; //一個單詞結(jié)束
}
}
return num;
}
由于是連續(xù)的字母定義為一個單詞陌选,就