gpt4 book ai didi

c - C语言中如何计算文本文件中每行的字数

转载 作者:行者123 更新时间:2023-11-30 18:11:04 25 4
gpt4 key购买 nike

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

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

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

关于c - C语言中如何计算文本文件中每行的字数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52358624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com