c - printLongestLine 打印无关信息

标签 c

我有这个函数 printLongestLine,我想打印每行输入的长度以及最大长度。例如,如果输入是:

Hey
I love stack

输出应该是:

The length of line 1 is 3
The length of line 2 is 15
The greatest line length is 15

但实际输出是:

The length of line 1 is 3
The length of line 2 is 15
The length of line 3 is -858993460
The length of line 4 is -858993460
The length of line 5 is -858993460
The length of line 6 is -858993460
The length of line 7 is -858993460
The length of line 8 is -858993460
The length of line 9 is -858993460
The length of line 10 is -858993460
The length of line 11 is -858993460
The length of line 12 is -858993460
The length of line 13 is -858993460
The length of line 14 is -858993460
The length of line 15 is -858993460
The length of line 16 is -858993460
The length of line 17 is -858993460
The length of line 18 is -858993460
The length of line 19 is -858993460
The length of line 20 is -858993460
The greatest line length is 15

我已尝试修复 for 循环,但没有看到遍历我的 lineLength 数组的错误无济于事。

#define NEWLINE 1
#define MAXLINES 20 //max number of lines
#define IN 0

//Precondition - Lines that are only /n will not be printed.
//Postcondition - prints the lengths of all the lines, and then the max line length of the input
printLongestLine()
{
    int lineLength[MAXLINES];
    int currentLine = 0;
    int status = NEWLINE;
    int currentLength = 0;
    int c;
    while ((c = getchar()) != EOF)
    {

        if ((c == '\n'))   
        {
            status = NEWLINE;
            lineLength[currentLine] = currentLength;
            currentLine++;
        }
        else if ((status == NEWLINE))
        {
            status = IN;
            currentLength++;

        }
        else
        {
            status = IN;
            currentLength++;
        }
    }
    int maxLength = 0;
    for (int i = 0; i < MAXLINES; i++)
    {
        if (lineLength[i] > maxLength)
        {
            maxLength = lineLength[i];
            printf("The length of line %d is %d\n", (i + 1), lineLength[i]);
        }
        else if ((lineLength[i] == 0) || lineLength[i] == NULL)
            continue;
        else
            printf("The length of line %d is %d\n", (i + 1), lineLength[i]);
    }
    printf("The greatest line length is %d", maxLength);
}   

最佳答案

您应该只迭代到您计算过的范围:

for (int i = 0; i < currentLine; i++) {
  // ...
}

关于c - printLongestLine 打印无关信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56436061/

相关文章:

c - 我的自定义操作系统内核中的 VGA 显示问题

c++ - 获取 HPUX 上正在运行的进程的可执行文件的完整路径

c - 为什么 C 代码中的 1.0f 在生成的程序集中表示为 1065353216?

c - 错误 - 在 C 中执行的时间

c - 如何使用 GCC 编译器强制执行结构位顺序?

c - 如何使用 ANSI C 获取文件的 sha256 哈希值

C套接字编程: client send() but server select() doesn't see it

c - 字符串和指针

使用 Python 和共享库的复杂 Makefile

c - GCC 会内联一个接受指针的函数吗?