// 获取最长文本行 #include <stdio.h> #define MAXLINE 10 // maximum input line length int getline(char line[], int maxline); void copy(char to[], char from[]); // Print the largest input line int 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) { // 输出行长度及行内字符串 printf("length: %d, line: %s", len, line); // 当前遇到的最长字符行 if (len > max) { max = len; copy(longest, line); } } // 存在最长行 if (max > 0) { printf("The longest line : %s/n", longest); } return 0; } // getline: read a line into s (include '/n' and '/0'), return length int getline(char s[], int lim) { int c, i, j; // 调用的时候实参是设定的最大长度,所以下面操作不会出现越界。 // 此处是lim-2是因为还要存放最后一个'/n'和一个'/0'。 // 此处j记录的是复制的字符个数,i只是记录了文本行的真实长度, // 但是要存放超出MAXLINE的字符还要多分配空间才可以,否则会越界 j = 0; for (i = 0; (c = getchar()) != EOF && c != '/n'; ++i) { if (i < lim -2) { s[j] = c; ++j; } } if (c == '/n') { s[j] = c; ++j; ++i; } s[j] = '/0'; return i; } // copy: copy 'from' into 'to'; assume to is big enough void copy(char to[], char from[]) { int i; for (i = 0; (to[i] = from[i]) != '/0'; ++i) ; }