c_exercises/1-16.c

46 lines
979 B
C

#include <stdio.h>
#define MAXLINE 1000 /* maximum input line length */
/* ggetline: read a line into 'line', return length */
int ggetline(char line[], int maxline){
int c, i;
for (i=0; (c=getchar()) != EOF && c!='\n'; ++i){
if (i<maxline-1){
line[i]=c;
}
else if (i==maxline-2){
line[i]='\n';
line[i++]='\0';
}
}
return i;
}
/* copy: copy 'from' into 'to'; asume to is big enough */
void copy(char to[], char from[]){
int i;
i = 0;
while((to[i] = from[i]) != '\0'){
++i;
}
}
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 = ggetline(line, MAXLINE)) >0){
if (len > max){
max = len;
copy(longest, line);
}
}
if (max > 0){ /* there was a line */
printf("%s\n", longest);
printf("length: %d\n", max);
}
return 0;
}