From bfce8f0d0d828209ec0bec71371ee94a7ad62d3e Mon Sep 17 00:00:00 2001 From: Michael Hunteman Date: Tue, 4 Jul 2023 17:03:53 -0500 Subject: Initial commit --- one/longest.c | 86 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 one/longest.c (limited to 'one/longest.c') diff --git a/one/longest.c b/one/longest.c new file mode 100644 index 0000000..cf19ac9 --- /dev/null +++ b/one/longest.c @@ -0,0 +1,86 @@ +#include + +#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; +} -- cgit v1.2.3