"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."
Here is the full code in the K&R answer book for exercise 1.16:
#include <stdio.h>
#define MAXLINE 1000
int getline (char line[], int maxline);
void copy (char to[], char from[]);
main()
{
int len;
int max;
char line[MAXLINE];
char longest[MAXLINE];
max = 0;
while ((len = getline(line, MAXLINE)) > 0 ){
printf("%d %s", len, line);
if (len >max){
max = len;
copy (longest, line);
}
}
if (max > 0)
printf("%s", longest);
getchar();
return 0;
}
int getline(char s[], int lim)
{
int c, i, j;
j = 0;
for (i = 0; (c = getchar()) != EOF && c != '\n'; ++i)
if (i < lim-2){
s[j] = c;
++j;
}
if (c == '\n'){
s[j] = c;
++j;
++i;
}
s[j] = '\0';
return i;
}
void copy (char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
Looking at the getline function, what is the purpose of having lim-2 instead of lim-1 in the following line:
if (i < lim-2){
This doesn't seem to serve any purpose at all. Shouldn't the '\0' character marker occur at s[lim] and not s[lim-1] or s[lim-2]?
Also, the function skips whatever the latest character was, if it goes over the character limit, until it finds a new line character, and it adds the newline character to the char string, but skips whatever the next "fittable" character coming from the input stream in the process. What is this purpose of this?
I'm not really sure what the author was intending here, and the book offers no explanation.
edit: Using an array such as line[5], I was under the impression that the NULL character in a character array goes in line[5], and we get to put something in the array subscripts 0-4. Is this assumption false?