C程序设计语言第一章练习题1-16
练习1-16 修改打印最长文本行的程序的主程序main,使之可以打印任意长度的输入行的长度,并尽可能多地打印文本。
#include <stdio.h>
#define MAX_LINE 10
int getline(char[], int);
void copy(char to[], const char from[]);
int main() {
int len;
int max;
char line[MAX_LINE];
char longest[MAX_LINE];
max = 0;
while ((len = getline(line, MAX_LINE)) > 0) {
if (len > max) {
max = len;
copy(longest, line);
}
}
if (max > 0) {
printf("%s", longest);
}
}
int getline(char s[], int len) {
int c, i;
// 直接将行中的字符复制到字符数组s中
for (i = 0;; ++i) {
c = getchar();
if (c == EOF || c == '\n') break; // 当前行少于 len
if (i < len - 1) s[i] = (char) c; // 当前行超出 len
}
if (i > len - 1)
s[len - 1] = '\0'; // 如果行的长度大于 len 在s结尾处写入 \0
else
s[i] = '\0'; // 如果行长度小于 len,在长度i的位置写入 \0
// s[(i > len - 1) ? (len - 1) : i] = '\0'; // 以上 if else 使用三元运算符的简写形式
return i;
}
void copy(char to[], const char from[]) {
for (int j = 0;; ++j) {
to[j] = from[j];
if (from[j] == '\0') break;
}
}
解题思路参考:https://www.cnblogs.com/DeadGardens/p/4781076.html