【问题标题】:How can I enumerate text read from a file line by line, and find the line with the most characters and words in C?如何逐行枚举从文件中读取的文本,并找到 C 中字符和单词最多的行?
【发布时间】:2016-02-05 20:46:32
【问题描述】:

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

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

这是我的代码

#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;
}

【问题讨论】:

  • 您对 c# 解决方案满意吗?或者只是将每种语言相似!标记为C
  • 以单词或字符为单位测量行长。它比迄今为止最长的更长吗?如果是这样,请坚持下去。重复到文件末尾。
  • 如果您阅读带有fgets 的行,任务会更容易。
  • 您通过复制代码来“计算字数”,例如,stackoverflow.com/q/23609836/2564301?
  • @Jongware 实际上,没有。我从一本教科书中读到它,该教科书建议复制它的代码并通过尝试枚举和比较单词的数量来进一步研究它。

标签: c++ c io lines


【解决方案1】:

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

int highestCharCount = 0;
int currentCharCount = 0;

跟踪字符数

++currentCharCount;

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

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

在获得换行符的同时重置它。

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

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

【讨论】:

    猜你喜欢
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 2019-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多