From 2d04791820175079daea868135ea04cf7cc5be0c Mon Sep 17 00:00:00 2001 From: Abigail Date: Mon, 3 May 2021 18:33:56 +0200 Subject: C solution for week 111, part 2 --- challenge-111/abigail/README.md | 1 + challenge-111/abigail/c/ch-2.c | 60 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 challenge-111/abigail/c/ch-2.c diff --git a/challenge-111/abigail/README.md b/challenge-111/abigail/README.md index 53215ce77d..3f7fc99b5f 100644 --- a/challenge-111/abigail/README.md +++ b/challenge-111/abigail/README.md @@ -51,6 +51,7 @@ to standard output. In case of ties, we print the first one found. ### Solutions * [GNU AWK](awk/ch-2.gawk) +* [C](c/ch-2.c) * [Perl](perl/ch-2.pl) ### Blog diff --git a/challenge-111/abigail/c/ch-2.c b/challenge-111/abigail/c/ch-2.c new file mode 100644 index 0000000000..a677e4cad6 --- /dev/null +++ b/challenge-111/abigail/c/ch-2.c @@ -0,0 +1,60 @@ +# include +# include +# include +# include +# include + +/* + * See ../README.md + */ + +/* + * Run as: cc -o ch-2.o ch-2.c; ./ch-2.o < input-file + */ + +int main (void) { + char * line = NULL; + size_t len = 0; + char * longest = NULL; + size_t longest_size = 0; + + while (getline (&line, &len, stdin) != -1) { + /* + * First check whether the word has its characters + * in lexical order. + */ + size_t i = 0; + bool in_order = 1; + while (line [i] != '\n') { + if ((i && tolower (line [i]) < tolower (line [i - 1])) || + !isalpha (line [i])) { + in_order = false; + break; + } + i ++; + } + + /* + * If we have a word with its characters in lexical order, and + * it's longer than the longest word found, keep the word. + */ + if (in_order && i > longest_size) { + longest_size = i; + if ((longest = (char *) realloc (longest, (i + 1) * sizeof (char))) + == NULL) { + perror ("Realloc failed"); + exit (1); + } + for (size_t j = 0; j <= i; j ++) { /* Copies the newline as well */ + longest [j] = line [j]; + } + longest [i + 1] = '\0'; + } + } + printf ("%s", longest); + + free (line); + free (longest); + + return (0); +} -- cgit