我正在学习C语言和它要在文本文件中读取的任务之一,并让它输出格式化的文本文件。最终产品应如下所示:

1)"I must not fear.[4,17]
2)Fear is the mind-killer.[4,24]
3)Fear is the little-death that brings total obliteration.[8,56]
4)I will face my fear.[5,20]
.
.
.
13)oneWord_allAlone[1,16]
13 lines, 94 words, 481 characters
Line 10 has the most words (16)
Line 7 has the most characters (68)

我已经写了代码,可以得到一些接近的东西,但信息是无序的,变量是错误的,它切断了每个句子的第一个字母。我得到:
I must not fear0.)
[4, 16]
ear is the mind-killer.0)
[7 39]
ear is the little-death that brings total obliteration.0)
[14 92]
.
.
.
neWord_allAlone1)
[86 470]
1 lines, 20360 words, 110685 characters
line 1 has the most words with (86)
line 1 has the most characters with 470)

我看不到110685个字符。这么说,我做错什么了?据我所知,我已正确设置了所有变量,但输出顺序错误,第一个字符被截断,计数为wayyyy off。非常感谢您的帮助!这是我的代码:
#include <stdio.h>

#define IN 1
#define OUT 0

void main() {

  int c = 0;
  int numChars = 0;
  int numWords = 0;
  int numLines = 0;
  int state = OUT;
  int test = 0;
  int largestNumChars = 0;
  int largestNumWords = 0;
  int totalNumChars = 0;
  int totalNumWords = 0;
  int lineWithMostChars = 0;
  int lineWithMostWords = 0;

  FILE *doesthiswork = fopen("testWords.in", "r");
  while ((test = fgetc(doesthiswork)) != EOF) {
    if ( test == '\n') {
            ++numLines;
    }
    while ((test = fgetc(doesthiswork)) != '\n') {
        ++numChars;
        putchar(test);
        if (test == ' ' || test == '\t' || test == '\n') {
          state = OUT;
        } else if (state == OUT){
          state = IN;
          ++numWords;
        }
        totalNumWords = totalNumWords + numWords;
        totalNumChars = totalNumChars + numChars;
     }

     if (largestNumChars == 0)  {
       largestNumChars = numChars;
     } else if (largestNumChars < numChars) {
       largestNumChars = numChars;
       lineWithMostChars = numLines;
     } else  {
       largestNumChars = largestNumChars;
       lineWithMostChars = lineWithMostChars;
     }

     if (largestNumWords == 0)  {
       largestNumWords = numWords;
       lineWithMostWords = numLines;
     } else if (largestNumWords < numWords) {
       largestNumWords = numWords;
       lineWithMostWords = lineWithMostWords;
     } else {
       largestNumWords = largestNumWords;
     }

     printf("%d) %c [%d %d]\n",numLines, test, numWords, numChars);
   }

   printf("%d lines, %d words, %d characters\n",
     numLines, totalNumWords, totalNumChars);
   printf("line %d has the most words with (%d)\n",
     lineWithMostWords, largestNumWords);
   printf("line %d has the most characters with (%d)\n",
     lineWithMostChars, largestNumChars);
}

最佳答案

好吧,最初的字母是你在第一次通话时读的,但你不像在第二次通话时读的那样。
fgetc是如此之大,因为您周期性地向它添加putchar,但您永远不会将fgetc重置为零。
我希望这能有帮助。找到并压扁那些虫子,玩得开心!

关于c - 在ANSI C中读取和格式化文本文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25597737/

10-13 03:20