Sorry if this has been asked before. I've found various (and probably way more efficient) solutions to this exercise but I'm kind of puzzled by mine in particular not producing any useful output.
This is the original code from the example in chapter 1.9
#define MAXLINE 1000
int getline(char line[], int maxline);
void copy(char to[], char from[]);
/* print longest input line */
main() {
int len; /* current line length */
int max; /* maximum length seen so far */
char line[MAXLINE]; /* current input line */
char longest[MAXLINE]; /* longest line saved here */
max = 0;
while ((len = getline(line, MAXLINE)) > 0)
if (len > max) {
max = len;
copy(longest, line);
}
if (max > 0) /* there was a line */
printf("%s", longest);
return 0;
}
/* getline: read a line into s, return length */
int getline(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') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[]) {
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
The task is to revise the main routine of the longest-line program so it will correctly print the length of arbitrarily long input lines, and as much as possible of the text. Some solutions modify getline() but it reads like I'm supposed to modify main() so that's what I decided to try.
What came to mind is to implement a secondary line length counter and compare it to MAXLINE to decide what message to print. I came up with a fairly simple loop in a separate little program.
#include <stdio.h>
main() {
int c, i, ll;
ll = 0;
while ((c = getchar()) != EOF)
for (i = 0; (c=getchar()) != EOF && c != '\n'; ++i)
if (i > ll)
ll = i;
printf("%d\n", longest);
}
This works fine on its own, but when I add it back in, it outputs 0 every time. If I move the loop above the other one, I get no output at all. I compiled with GCC with -ansi and -pedantic flags and there were no warnings so likely something simple is flying over my head (It's also my first language).
modified main():
main() {
int i,c, ll; /* additional line length counter */
int len; /* current line length */
int max; /* maximum length seen so far */
char line[MAXLINE]; /* current input line */
char longest[MAXLINE]; /* longest line saved here */
max = 0;
while ((len = getline(line, MAXLINE)) > 0)
if (len > max) {
max = len;
copy(longest, line);
}
ll = 0;
while ((c = getchar()) != EOF)
for (i = 0; (c = getchar()) != EOF && c != '\n'; ++i)
if (i > ll)
ll = i;
if (max > 0 && ll > max)
printf("Line length limit exceeded (%d characters), output will be truncated.\n%s...\n", ll, longest);
else if (max > 0 && ll < max) /* there was a line */
printf("%s\n", longest);
return 0;
}