-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlongest-line.c
48 lines (43 loc) · 1.18 KB
/
longest-line.c
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
#include <stdio.h>
// maximum length of input line
#define MAX_LINE_LENGTH 100
// reads character and puts in line[] and returns its length
int get_line(char line[]) {
int c, i;
// add character to line string if its valid
for (i = 0; i < MAX_LINE_LENGTH - 1 && (c = getchar()) != '\n' && c != EOF;
i++)
line[i] = c;
// add new line encountered at the end of the line
if (c == '\n') {
line[i] = c;
i++;
}
// put null character at the end of line to make it valid string
line[i] = '\0';
return i;
}
// copy string (or array) of characters
void copy(char *from, char *to) {
while ((*to++ = *from++))
;
}
int main() {
char current_line[MAX_LINE_LENGTH];
char longest_line[MAX_LINE_LENGTH];
int longest_length = 0;
int current_line_length;
while ((current_line_length = get_line(current_line)) > 0) {
if (current_line_length > longest_length) {
longest_length = current_line_length;
copy(current_line, longest_line);
}
}
// print if any valid longest line is found
if (longest_length > 0) {
printf("longest line is given below:\n");
printf("%s", longest_line);
} else
printf("no longest line found");
return 0;
}