[英]How to count the number of words per line in a text file in 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
...
请使用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
您当然需要处理代码中的最后一行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.