【发布时间】:2014-05-08 09:07:44
【问题描述】:
我必须为作业编写一个程序来扫描文本文件并说出有多少句子(基于句号,没有其他标点符号)总单词数和总次数词出现。我可以计算总字数,但具体的字数和句子数让我望而却步,我相信我们应该使用fscanf。这是我所拥有的
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
FILE *datafile;
int main(){
int count1, count2, leng, sentences ;
char filename[50], word[120], sentence[120];
printf("Enter a word :");
gets(word);
printf("Enter the filename:");
gets(filename);
datafile = fopen(filename, "r");
if(datafile == NULL) {
printf("Error , Can not open %s", filename);
exit(249);
}
leng = 0;
count2 = 0;
sentences = 0;
while (fscanf(datafile, "%s", word) == 1) { //this one works
++leng;
}
while (!feof(datafile))
{
fscanf(datafile,"%s",word);
if (strcmp(word,"the")==0)
count2++;
}
while(fscanf(datafile, "%s", word) == '.') {
++sentences;
}
printf("There are a total of %d words\n", leng);
printf("The word '%s' appears %d times\n", word, count2);
printf("There are %d sentences", sentences);
}
当我运行它时,我得到
我尝试了两种不同的方法来计算句子计数和特定字数,但我真的不明白为什么第一种也有效,我想一旦我有了其中一种,另一种将是相同的格式。感谢您提供任何帮助或建议。
【问题讨论】:
-
fscanf 返回成功匹配和分配的输入项的数量,可以少于提供的数量,如果早期匹配失败,甚至为零。您正在将一个 int 值与 '.' 进行比较。 .
-
请注意,您应该使用
fgets(word, sizeof(word), stdin);而不是gets(word);以避免缓冲区溢出。