C程序计算输入文件中的总字数

输入文件在第2行包含一个完全空行,在文本的最后一个句号后包含一个不必要的空格。 有了这个输入文件,我得到48个单词,而我想要得到46个单词。

我的输入文件包含:
“查尔斯达尔文从”双城记“开幕

这是最好的时期,这是最糟糕的时期。 这是智慧的时代,是愚蠢的时代。 这是信仰的时代,是令人怀疑的时代。 “

这是我尝试的方式:

#include  #include  #include  #include  #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 ,如果我没有弄错的话。

这些方面的东西:

 while ((ch = fgetc (file_story)) != EOF) { if (ch == ' ') { num_words++; while( (ch = fgetc (file_story)) == ' ' && (ch != EOF) ) } if (ch == '\n') { num_words++; while( (ch = fgetc (file_story)) == '\n' && (ch != EOF) ) } 

虽然我想知道为什么你只是用空格和换行符来计算新单词。 在您的代码中,绝对不会使用其他一些标点符号分隔的两个单词

我的建议是更改单词计数循环如下:

 /* count words */ num_words = 0; int flag = 0; // set 1 when word starts and 0 when word ends while ((ch = fgetc (file_story)) != EOF) { if ( isalpha(ch) ) { if( 0 == flag ) // if it is a first letter of word ... { num_words++; // ... add to word count flag = 1; // and set flag to skip not first letters } continue; } if ( isspace(ch) || ispunct(ch) ) // if word separator ... { flag = 0; // ... reset flag } }