如何计算C中文本文件中每行的单词数

时间:2018-09-16 21:40:05

标签: c

我希望能够逐行读取文件并计算每行有多少个单词。这是我到目前为止的内容:

int countWords(char* filename)
{
   int wordCount=0;
   int lineCount=0;

   FILE *ptr_file;
   char buf[1000];
   ptr_file = fopen(filename,"r");

   if (!ptr_file) {
     return 1;
   }

   while (fgets(buf,1000,ptr_file) != NULL) {
     int len = strlen(buf);
     for(int x=0; x<len; x++) {
       if (buf[x]!=' ' && buf[x+1]==' '){
         wordCount++;
       }
       else if (buf[x]=='\n') {
         lineCount++;
         printf("Line %d: %d words", lineCount, wordCount);
         wordCount=0;
       }
       printf("%d",wordCount);
     }

   }

   fclose(ptr_file);

   return 0;
}

我对C语言很陌生,因此仍然习惯于使用整个指针。当我运行该程序时,没有任何输出。这是我正在寻找的输出类型:

Line 1: 3 words
Line 2: 5 words
...

1 个答案:

答案 0 :(得分:-1)

请使用GCC(gcc test.c -o test)编译以下代码:

#include <stdio.h>
#include <string.h>

    main() {
       int wordCount=0;
       int lineCount=0;

       FILE *ptr_file;
       char buf[1000];
       ptr_file = fopen("test.txt", "r");

       if (!ptr_file) {
         return 1;
       }

       while (fgets(buf,1000,ptr_file) != NULL) {
         int len = strlen(buf);
         int x;
         for(x=0; x<len; x++) {
           if (buf[x+1]==' '){
             wordCount++;
           }else if (buf[x]=='\n') {
             lineCount++;
             wordCount++;
             printf("Line %i: %i words\n", lineCount, wordCount);
             wordCount=0;
           }
         }

       }

       fclose(ptr_file);

       return 0;
}

test.txt文件:

word1 word2 word3 word4
word1 word2
word1
word1 word2 word3 word4 word5

输出:

Line 1: 4 words
Line 2: 2 words
Line 3: 1 words
Line 4: 5 words
Line 5: 1 words

您需要处理代码中的最后一行