printLongestLine打印无关信息

时间:2019-06-04 00:41:58

标签: 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);
}   

1 个答案:

答案 0 :(得分:2)

您应该只迭代一次:

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