输入文件在第 2 行包含一个完全空的行,并且在文本的最后一个句点之后包含一个不必要的空格。使用这个输入文件,我得到了 48 个单词,而我应该得到 46 个单词。
我的输入文件包含:
“从查尔斯 Darwin 的两个城市的故事开始
这是最好的时代,也是最坏的时代。那是个时代 智慧的时代,是愚昧的时代。那是一个时代 信仰,这是怀疑的时代。 "
这是我的尝试:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define max_story_words 1000
#define max_word_length 80
int main (int argc, char **argv)
{
char story[max_story_words][max_word_length] = {{0}};
char line[max_story_words] = {0};
char *p;
char ch = 0;
char *punct="\n ,!.:;?-";
int num_words = 1;
int i = 0;
FILE *file_story = fopen ("TwoCitiesStory.txt", "r");
if (file_story==NULL) {
printf("Unable to open story file '%s'\n","TwoCitiesStory.txt");
return (EXIT_FAILURE);
}
/* count words */
while ((ch = fgetc (file_story)) != EOF) {
if (ch == ' ' || ch == '\n')
num_words++;
}
rewind (file_story);
i = 0;
/* read each line in file */
while (fgets (line, max_word_length, file_story) != NULL)
{
/* tokenize line into words removing punctuation chars in punct */
for (p = strtok (line, punct); p != NULL; p = strtok (NULL, punct))
{
/* convert each char in p to lower-case with tolower */
char *c = p;
for (; *c; c++)
*c = tolower (*c);
/* copy token (word) to story[i] */
strncpy ((char *)story[i], p, strlen (p));
i++;
}
}
/* output array */
for(i = 0; i < num_words; i++)
printf ("story[%d]: %s\n", i, story[i]);
printf("\ntotal words: %d\n\n",num_words);
return (EXIT_SUCCESS);
}
最佳答案
您的 num_words
考虑了两个额外的空格,这就是您得到 48 的原因。
如果我没记错的话,你应该在 fgets
-strtok
循环之后立即打印 i
。
关于C程序计算输入文件中的总字数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29506556/