1

继续查看这篇文章的底部以了解实际问题

我可能试图过多地理解真正简单的事情,但在我弄清楚这一点之前我无法继续。

在阅读 K&R 1.9 字符数组时,您遇到了一个示例程序,该程序接受输入并确定哪一行最长,然后重新打印它。

为了理解这个程序的getline函数,我稍微修改了一下,在它的运行过程中打印了一些信息。现在我发现了一些输入,一旦我理解了这些输入,应该会大大增强我对 getchar() 的理解。


附带说明一下,当我尝试从库中读取源代码时,我完全不知所措。例如,我尝试寻找 getchar() 并最终目瞪口呆地盯着#endifstddef.h 的第 300 行某处的 18 座塔。我将通过在不久的将来停止对 stdio.h 中的功能的追求来避免这种头痛。图书馆很难找到东西是正常的吗?该函数不应该作为可读源存在,还是我只是抱有希望?


为方便起见,我将继续从 K&R 发布整个修改后的程序:

#include <stdio.h>
#define MAXLINE 5   /* maximum input line length */

int getline(char line[], int maxline);
void copy(char to[], char from[]);

/* print the longest input line */
main()
{
    int len;            /* current line length */
    int max;            /* maximum length seen so far */
    char line[MAXLINE];    /* current input line */
    char longest[MAXLINE]; /* longest line saved here */
    max = 0;
    while ((len = getline(line, MAXLINE)) > 0)
        if (len > max) {
            max = len;
            copy(longest, line);
        }
    if (max > 0)  /* there was a line */
        printf("%s\n", longest);
        printf("INFO: max = %d\n", max);
        printf("INFO: sizeof s[] = %d", sizeof longest);
    return 0;
}

/* getline:  read a line into s, return length  */
int getline(char s[],int lim)
{
    int c, i;
    for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i){
        s[i] = c;
        printf("INFO: s[%d] = %c\n", i, c);
    if (c == '\n') {
        printf("INFO: %d\n", i);
        printf("INFO: s[%d] = \\n\n", i);
        s[i] = c;
        ++i;}
    }
    s[i] = '\0';
    return i;
}

/* copy:  copy ’from’ into ’to’; assume to is big enough */
void copy(char to[], char from[])
{
    int i;
    i = 0;
    while ((to[i] = from[i]) != '\0')
        ++i;
}

这是一些示例输入/输出:我正在使用 CodeBlocks 和 Windows 7

sampleIO

Finally, my question is why does the for loop in the getline() function leave the loop after it gets to F and therefore places the null terminator after F as \0

My hypothesis is that perhaps putting the EOF character shown as ^Z in the windows terminal, the array is truncated to a length of 4 characters plus a null terminator. It turns out if I put the EOF character inside a line to be read, the saved line s[] will only contain a maximum size of 5. What also confuses me is that the variable len will always be 0, is that because len is assigned during the while loop in main(), and does not have its value saved once that while loop is broken?

Something interesting to me, but probably not to experienced C users, is that the if statement right after the for loop in getline() can either be inside the for loop, or outside and it does not change the program. Interesting, because won't that mean that whether or not the for loop executes any code in the body, at the very least (c=getchar()) is executed?

Sorry the question is so wordy, I appreciate any helpful comments/answers.

4

1 回答 1

6

Because MAXLINE is 5, and the getline function never reads more than MAXLINE - 1 characters.

于 2012-11-12T08:18:34.053 回答