C程序计算文件中的符号(没有\ n \ t'')并打印具有大多数符号的行和符号数量最少的行

问题描述 投票:-2回答:3

所以我对大学有这个大的帮助,我是编程的初学者,我需要对我正在编写的这个程序提供一些帮助。所以基本上我必须编写一个程序来计算文件中每一行的符号和字符(没有'\ n','\ t','')并打印出符号和字符最多的行以及最少的行。 例如,如果我在文件中 你好,我的名字是马丁 我喜欢吃肉丸 3.Bacon很棒

它应该打印出来例如:

“行号1的字符最多,行号3的字符最少”。

for (c = getc(fp); c != EOF; c = getc(fp))
{
   if(c=='\n')
   {
      lines++;
   }
   if (c != '\n' && c != '\t' && c!= ' ')
   {
      count++;
   }
}

我做了符号计数和行数,但其他一切都是黑暗的。请帮助谢谢。

c
3个回答
1
投票

**编辑**我的道歉,谢谢你指出了不足之处。

根据分配说明的含义,您不需要计算整个文本文件中的符号总数,而是计算每行的符号总数。对于具有最少符号的行号,具有最少符号的行,具有最多符号的行号以及最大符号量,具有一些变量。每次读取一行时,只要该字符不是'\ n',就有一个临时变量来计算非空格符号。到达'\ n'后,检查1)当前行数是否小于最小计数或2)当前行数大于最大计数。如果是,请更新新计数和新行号。

我把它编码为:

int lineNO = 1;
int leastLine, mostLine, currCount, leastCount, mostCount = 0;
int c;

while ((c = getc(fp)) != EOF) {
   if (c == '\n') {
      /* check if currCount < leastCount or if currCount > mostCount */
      /* if so, update the necessary lineNO's */
      currCount = 0;
      lineNO++;
   }

   if (c != '\n' && c != '\t' && c!= ' ') {
      currCount++;
   }   
}

0
投票

非常感谢您的帮助。我能够编写程序并找到leastLine - 这是代码:

         int lineNO = 1;
         int  mostLine, currCount, leastCount[200], mostCount = 0;
          int c;
         int len=0;
           int leastLine[200];
              while ((c = getc(fp)) != EOF) {
          if (c == '\n') {
           currCount = 0;
            lineNO++;
              leastLine[lineNO]=lineNO;
          }

          if (c != '\n' && c != '\t' && c!= ' ') {
           currCount++;
             leastCount[lineNO]=currCount;
          }

       }
         int i;
       for(i=0;i<=lineNO;i++){
    if(leastCount[0]>leastCount[i]){
        leastCount[0]=leastCount[i];
        leastLine[0]=leastLine[i];
    }
     }



        printf("%d",leastLine[0]);

但是有一些问题:

1.如果我更改了这一行而不是leastCound [0]> leastCount [i]我改变大于小于我得到的东西,如“-327806”。

2.在我的“text.txt”文件(我测试程序的文件)中,如果第1行是最小行,则程序不将其计为最小值。

当我修改程序以打印所有数字和行时,我得到了这个:https://pasteboard.co/GY2wLq7.jpg


0
投票

而不是使用数组来跟踪行号及其长度,然后迭代数组以检查哪个行号具有最少的字符,我认为用我使用的变量跟踪计数会更容易上图:leastLine, mostLine, currCount, leastCount, mostCount

我在评论区域做的是:

if (currCount < leastCount) {
   leastCount = currCount;
   leastLine = lineNO;
}

else if (currCount > mostCount) {
   mostCount = currCount;
   mostLine = lineNO;
}

在while循环之后,您还需要在结尾处进行此检查,否则您将无法检查最后一行。 (除非你稍微修改while循环。)

如果你真的想用一个数组跟踪长度,我建议一个声明如下的数组:int lineLengths[200],其中索引(1 - 199,而不是0-199,因为行号从1开始,所以为了避免混淆,将索引0处的第一个元素留空会更容易)表示行号,索引处的值将是字符数。然后,您可以迭代此数组以查找最小和最大计数并存储两者的行号。

© www.soinside.com 2019 - 2024. All rights reserved.