K& R,找到最长的线,相同的代码但不工作?

时间:2017-12-07 10:22:22

标签: c kernighan-and-ritchie

我刚刚开始阅读K& R,在第32-33页,有一个代码

  

找到输入中最长的一行。

我几乎完全复制粘贴了本书中给出的代码,只添加了一些注释行,使代码对我来说更容易理解。但它没有用。

修改:对不起质疑我很抱歉。当我按Ctrl + Z时,程序似乎无法正常运行,以便终止它。无论我键入多少行以及按Ctrl + Z多少次,它都无效。

以下是我的代码版本:

/* Find the longest line among the giving inputs and print it */

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

int getLine(char line[], int maxLine);
void copy(char to[], char from[]);

int main(void) {
    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;

    /* getLine function takes all the input from user, returns it's size and equates it to the variable len
     * Then, len is compared whether it's greater than zero because if there's no input, no need to do any calculation
     * EDGE CASE
     */
    while ((len = getLine(line, MAXLINE)) > 0)
        /* If the length of input is larger than the previous max length, set max as the new length value and copy that input */
        if (len > max) {
            max = len;
            copy(longest, line);
        }
    if (max > 0) /* there was a line, EDGE CASE */
        printf("%s", longest);

    return 0;
}

/* Read a line into s, return length.
 * Since the input length is unknown, there should be a limit */
int getLine(char s[], int lim) {
    int c, i;

    /* The loop's first condition is whether the input length is below the limit. EDGE CASE
     * If it's not, omit the rest because it would cause a BUFFER OVERFLOW. Next, take the input as long as it's not an EOF command.
     * Finally, if the input is end of line, finish the loop, don' take it.
     */
    for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++)
        s[i] = c;
    if (c == '\n')
        s[i++] = c;
    s[i++] = '\0'; // always put a '\0' character to a string array ending, so that the compiler knows it's a string.
    return i;
}

void copy(char to[], char from[]) {
    int i = 0;

    // This loop is readily assigns all chars from the source array to the target array until it reaches the ending char.
    while ((to[i] = from[i]) != '\0')
        ++i;
}

提前致谢!

1 个答案:

答案 0 :(得分:3)

好的,这是错误:

s[i++] = '\0'; // always put a '\0' character to a string array ending, so that the compiler knows it's a string.

这将导致它终止字符串,即使没有输入(当它直接得到EOF时),并且因为它在返回之前递增igetLine()将永远不会返回0并且因此main()永远不会停止。删除++修复它,进行简单测试。

此外,评论具有误导性,编译器也不知道任何事情。代码运行时编译器不再存在;字符串的内存格式是保持运行时库快乐的必要条件,因为这是他们所期望的。