我的程序需要从文本文件获取输入并将其输出在单行上。

但是,如果单行上的字符数超过60,则应该换行。

我到目前为止的代码:

 int main(int argc, char *argv[]){
 FILE *pFile;
 char x[10];
 char *token;
 pFile = fopen("test5.txt","r");
 int wordLength;
 int totalCharLength;
 char newline[10] = "newline";


 if(pFile != NULL){
        while (fgets(x, sizeof(x), pFile) != NULL) {
         token = strtok(x,"\r\n");
         if(token != NULL){
                printf("%s",x);

            }

         else{
                printf("%s",x);
        }
        //counter++;
        wordLength = strlen(x);
        totalCharLength += wordLength;
        printf("%d",totalCharLength);
        if(totalCharLength == 60){
            printf("%s",newline);
        }

    }

        fclose(pFile);
}
}

文本文件:
 a dog chased

 a cat up the

 tree. The cat

 looked at the dog from

 the top of the tree.

共有5行。哪个显示。这并不仅限于一行。

输出:
 a dog chased a cat up the tree. The cat looked at the dog from the top of the tree.

现在,程序需要能够以该格式获取输入文本并在一行中打印出来。

因此,上面的输出应该在第二个字符“dog”之前的第60个字符处换行。

但是,我想添加一个功能,以便有一个字符计数器,当字符数= 60时,它将打印新行。

现在,通过更多调试,我添加了代码
 printf("%d",totalCharLength);

就在if(totalCharLength == 60)行之前,我意识到这些字符是以随机增量而不是一一计数的。输出:
 a dog cha9sed 13a cat up 22the 26tree. The35 cat 40looked at49 the dog 58 from 63 the top o72f the tre81e.  85

因此,这表明它不会逐个字符地计数。但是,当我将charx [10]更改为较低的值时,它不会在一行上打印所有内容。它将留下空白。

示例:将charx [10]更改为charx [2]

正确地逐个字符地获取,但是输出不在一行中。

唯一应该换行的时间是当一行中的字符超过60个时。不是14(第一行)。
 a2 3d4o5g6 7c8h9a10s11e12d13 14
 30a17 18c19a20t21 22u23p24 25t26h27e28 29
 46t32r33e34e35.36 37T38h39e40 41c42a43t44 45
 71l48o49o50k51e52d53 54a55t56 57t58h59e60newline 61d62o63g64 65f66r67o68m69   70
 72t73h74e75 76t77o78p79 80o81f82 83t84h85e86 87t88r89e90e91.92 93 94

最佳答案

我认为您最好只是自己打印每个字符,并在添加换行符之前检查空格。

就像是:

((charCount > 60) && (currentChar == ' ')) {
    // print newline and reset counter
    printf("\n");
    charCount = 0;
}

编辑:
在进行任何检查之前,请检查当前字符是否已经是换行符并跳过它。
还要检查回车\r,因为在Windows中换行符是\r\n
#include <stdio.h>

int main(void) {
  FILE *f = fopen("test.txt", "r");
  if(!f) {
    printf("File not found.\n");
    return 1;
  }

  char c;
  int cCount = 0;
  while((c = fgetc(f)) != EOF) {
    if(c == '\r') continue;
    if(c == '\n') c = ' ';

    printf("%c", c);
    if((cCount++ > 60) && (c == ' ')) {
      printf("\n");
      cCount = 0;
    }
  }

  fclose(f);
  return 0;
}

关于c - 从文本文件一一计数字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33509070/

10-10 18:00
查看更多