summaryrefslogtreecommitdiff
path: root/one/longest.c
diff options
context:
space:
mode:
authorMichael Hunteman <michael@huntm.net>2023-07-04 17:03:53 -0500
committerMichael Hunteman <michael@huntm.net>2023-07-06 17:23:45 -0500
commitbfce8f0d0d828209ec0bec71371ee94a7ad62d3e (patch)
treebdf49ca788ca1ca030d5b1cccfd0c9dffeb3f69f /one/longest.c
Initial commit
Diffstat (limited to 'one/longest.c')
-rw-r--r--one/longest.c86
1 files changed, 86 insertions, 0 deletions
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 <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;
+}