如何逐行枚举从文件中读取的文本,并找到 C 中字符和单词最多的行

How can I enumerate text read from a file line by line, and find the line with the most characters and words in C?

本文关键字:字符 单词最 文本 枚举 逐行 文件 读取 何逐行      更新时间:2023-10-16

我目前正在编写一个程序,该程序应该从文本文件中读取(通过命令行提供给程序(,然后枚举并打印出每一行,并提供有关单词,字符和行数的信息,以及有关哪一行具有最多字符/单词的信息。

到目前为止,我已经能够让它计算单词、字符和行的数量,但很难找到一种方法来枚举和打印每一行并找到哪些行的字符/单词最多。

这是我的代码

#include <stdio.h>
#define IN 1
#define OUT 0
int main( )
{
int line, word, character, state, place, flag
    maxW, maxC;
state = OUT;
line = word = character = 0;
while( (place = getchar()) != EOF ) {
    ++character;
    flag = IN;
    printf("%c", place);
    if( place == 'n' ) {
        ++line;
        printf("%d: ", (line + 1));
        flag = IN;
    }
    if(flag == IN) {

    }
    if( place == ' ' || place == 'n' || place == 't' )
        state = OUT;
    else if( state == OUT ) {
        state = IN;
        ++word;
    }
}
printf("%d lines, %d words, & %d characters.n", line, word, character);
return 0;
}

创建本地最高字符数和当前字符数

int highestCharCount = 0;
int currentCharCount = 0;

跟踪字符数

++currentCharCount;

每个循环检查字符数是否高于最高字符数,如果是,则更改最高字符数。

If(currentCharCount > highestCharCount){
    highestCharCount = currentCharCount ;
}

获得新行字符的同时重置它。

if( place == 'n' ) {
    currentCharCount = 0;
    ++line;
    printf("%d: ", (line + 1));
    flag = IN;
}

这样,您最终将获得最高的字符数。