【问题标题】:Know the row with max characters (C)知道最大字符的行 (C)
【发布时间】:2012-06-22 21:11:38
【问题描述】:

我用 C 编写了一个程序,用于查找具有最大字符数

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int main (int argc, char *argv[])
{
    char c;                              /* used to store the character with getc */
    int c_tot = 0, c_rig = 0, c_max = 0; /* counters of characters*/
    int r_tot = 0;                       /* counters of rows */

    FILE *fptr;

    fptr = fopen(argv[1], "r");

    if (fptr == NULL || argc != 2)
    {
        printf ("Error opening the file %s\n'", argv[1]);
        exit(EXIT_FAILURE);
    }

    while ( (c = getc(fptr)) != EOF)
    {
        if (c != ' ' && c != '\n')
        {
            c_tot++;
            c_rig++;
        }

        if (c == '\n')
        {
            r_tot++;

            if (c_rig > c_max)
                c_max = c_rig;

            c_rig = 0;
        }
    }

    printf ("Total rows: %d\n", r_tot);          
    printf ("Total characters: %d\n", c_tot);
    printf ("Total characters in a row: %d\n", c_max);
    printf ("Average number of characters on a row: %d\n", (c_tot/r_tot));
    printf ("The row with max characters is: %s\n", ??????)

    return 0;
}

我可以轻松找到字符数最多的行,但如何打印

【问题讨论】:

  • 我认为这里说“行”而不是“行”更正确。
  • 请注意:在您的 while 循环中,您将 c 的值与 '\n' 进行了两次比较。您可以通过首先移动行检查并使用 else 子句来避免这种情况。在 else 子句中,您只需检查 if(c != ' ')
  • c 应该是 int,而不是 char,因为 EOF 不是 char 值。

标签: c file getc


【解决方案1】:

您需要存储具有最高字符数的行,例如在一个数组中。

如果您可以对行长做出假设,请声明两个字符数组:

char currentLine[255];
char maxLine[255];

使用getc 读取每个字符后,将其放入line 数组中。处理完该行后,如果当前行的计数较高,则将currentLine 的内容复制到maxLine 中,使用memcpy。您已经在跟踪c_totc_max 这两个数组的长度。

如果您不能对行长度做出假设,您可以使用相同的技术,但是当您遇到比初始大小更长的行时,您需要 mallocrealloc 缓冲区。

【讨论】:

  • 如果我的“c = getc”位于我需要的行的底部,我该如何存储该行?
  • 你有 c_rig 来索引当前的数组位置。然后你让 line[c_rig]=c;不要忘记在末尾添加 \0。
【解决方案2】:

您还应该将当前行存储在char * 中,并拥有一个最大的字符串char *。在确定最大大小的测试中,您还应该将当前行复制到最大的字符串。

不要忘记将最大的字符串初始化为“”,以免在零长度文件的情况下出错。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    相关资源
    最近更新 更多