diff options
-rw-r--r-- | 1/16.c | 43 |
1 files changed, 43 insertions, 0 deletions
@@ -0,0 +1,43 @@ | |||
1 | /* | ||
2 | Exercise 1-16. Revise the main routine of the longest-line program so it will | ||
3 | correctly print the length of arbitrarily long input lines, and as much as | ||
4 | possible of the text. | ||
5 | === | ||
6 | */ | ||
7 | |||
8 | #include <stdio.h> | ||
9 | |||
10 | #define MAX 1000 /* max line length */ | ||
11 | |||
12 | /* read line into string, l, of length size, s, return length */ | ||
13 | int readline(char l[], int s) { | ||
14 | int c, i; | ||
15 | for (i=0; i<s-1 && (c=getchar())!=EOF && c!='\n'; i++) | ||
16 | l[i]=c; | ||
17 | if (c=='\n') l[i++]=c; | ||
18 | l[i]='\0'; | ||
19 | return i; | ||
20 | } | ||
21 | |||
22 | /* copy string1, s1, to string2, s2 */ | ||
23 | void copy (char s1[], char s2[]) { | ||
24 | int i=0; | ||
25 | while ((s2[i]=s1[i])!='\0') i++; | ||
26 | } | ||
27 | |||
28 | int main () { | ||
29 | int l, m, c; /* length, max, character */ | ||
30 | char line[MAX], lngst[MAX]; /* line, longest */ | ||
31 | |||
32 | m=0; | ||
33 | while (l=readline(line, MAX)) { /* for each line */ | ||
34 | if (line[l-1]!='\n') /* if line exceeds buffer */ | ||
35 | while ((c=getchar())!=EOF && c!='\n') | ||
36 | l++; /* count remaining characters */ | ||
37 | if (l>m) { /* if longest */ | ||
38 | m=l; copy(line, lngst); /* record it */ | ||
39 | } | ||
40 | } | ||
41 | if (m) /* if lines were processed, print longest */ | ||
42 | printf("%d: %s\n", m-1, lngst); | ||
43 | } | ||