summaryrefslogtreecommitdiff
path: root/one/longest.c
blob: cf19ac92a6fefcc7867b0fe1bdc2db280cc945dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <stdio.h>

#define MAXLINE 1024

/*
 * read a line into s, return length,
 * assume length is less than MAXLINE
 * and the line number is less than MAXLINE
 */
int
get_line(char s[], int lim)
{
	int c, i;
	for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) {
		s[i] = c;
	}
	if (c == '\n') {
		/* increment i after assignment */
		s[i++] = c;
	}
	/* put null character at end of string */
	s[i] = '\0';
	return i;
}

/* copy from into to */
void
copy(char to[], char from[])
{
	int i = 0;
	/* '\0' marks end of string */
	while ((to[i] = from[i]) != '\0') {
		++i;
	}
}

/* remove trailing whitespace */
void
trim(char s[], int i)
{
	/* skip null character and new line */
	i -= 2;
	while (i >= 0 && (s[i] == ' ' || s[i] == '\t')) {
		--i;
	}
	s[i] = '\0';
}

/* flip characters in string */
void
reverse(char s[])
{
	int i = 0;
	while (s[i] != '\n') {
		++i;
	}
	--i;
	char c;
	for (int j = 0; j < i / 2; ++j) {
		c = s[i - j];
		s[i - j] = s[j];
		s[j] = c;
	}
}

/* print longest input line */
int
main()
{
	char line[MAXLINE], longest[MAXLINE];

	int len;
	int max = 0;
	while ((len = get_line(line, MAXLINE)) > 0) {
		if (len > max) {
			max = len;
			copy(longest, line);
		}
	}
	if (max > 0) {
		/* trim(longest, max); */
		/* reverse(longest); */
		printf("%s", longest);
	}
	return 0;
}