aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCian Bagshaw <cian@cianb.xyz>2023-05-07 09:15:11 +0100
committerCian Bagshaw <cian@cianb.xyz>2023-05-07 09:15:11 +0100
commit65def0aa82e45a2963d649624dbf93d42c7a3dc8 (patch)
tree1afb140e035b22f76c0111077da167f82fc87f50
parent22e879750bfb7bc80f409ac1a083ce3f7ae006d8 (diff)
downloadcProgLang-master.tar.bz2
cProgLang-master.zip
-rw-r--r--1/16.c43
1 files changed, 43 insertions, 0 deletions
diff --git a/1/16.c b/1/16.c
new file mode 100644
index 0000000..f276e88
--- /dev/null
+++ b/1/16.c
@@ -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 */
13int 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 */
23void copy (char s1[], char s2[]) {
24 int i=0;
25 while ((s2[i]=s1[i])!='\0') i++;
26}
27
28int 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}