{"content":{"id":537,"title":"K\u0026R Solutions - 1.16","body":"\u003cp\u003e\u003cb\u003eQ:\u003c/b\u003e 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.\u003c/p\u003e\r\n\u003cp\u003e\u003cb\u003eA:\u003c/b\u003e\u003c/p\u003e \r\n\u003cpre\u003e\u003ccode class=\"cpp\"\u003e...\r\nint main(void)\r\n{\r\n int len;\r\n int max;\r\n char line[MAXLINE];\r\n char longest[MAXLINE];\r\n\r\n max = 0;\r\n while ((len = get_a_line(line, MAXLINE)) \u003e 0) {\r\n if (len \u003e max) {\r\n max = len;\r\n copy(longest, line);\r\n }\r\n // Following tradition, we will be ignoring the null character that marks\r\n // the end of every string. The standard library function strlen() also\r\n // ignores null characters.\r\n printf(\"Length: %d\\n\", len - 1);\r\n printf(\"Line: %s\\n\", line);\r\n }\r\n if (max \u003e 0) {\r\n printf(\"%s\", longest);\r\n }\r\n\r\n return 0;\r\n}\r\n...\u003c/code\u003e\u003c/pre\u003e\r\n\u003cpre\u003e\u003ccode class=\"lisp\"\u003ehi\r\nLength: 2\r\nLine: hi\r\n\r\nthere this is an \r\nLength: 16\r\nLine: there this is an\r\n\r\narbitrarily long string\r\nLength: 23\r\nLine: arbitrarily long string\r\n\r\nmoo \r\nLength: 3\r\nLine: moo\r\n\r\narbitrarily long string\r\n\u003c/code\u003e\u003c/pre\u003e","publication_date":"2019-03-14T00:00:00.000Z","created_at":"2019-02-12T20:20:39.000Z","updated_at":"2019-02-12T20:44:42.000Z","user_id":1,"rating":null},"tags":"\u003ca class=\"changeable-title\" href=\"/q?tag=k%26r\"\u003ek\u0026amp;r\u003c/a\u003e \u003ca class=\"changeable-title\" href=\"/q?tag=programming\"\u003eprogramming\u003c/a\u003e \u003ca class=\"changeable-title\" href=\"/q?tag=answers\"\u003eanswers\u003c/a\u003e \u003ca class=\"changeable-title\" href=\"/q?tag=c\"\u003ec\u003c/a\u003e \u003ca class=\"changeable-title\" href=\"/q?tag=unix\"\u003eunix\u003c/a\u003e"}

K&R Solutions - 1.16

Q: 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.

A:

...
int main(void)
{
  int len;
  int max;
  char line[MAXLINE];
  char longest[MAXLINE];

  max = 0;
  while ((len = get_a_line(line, MAXLINE)) > 0) {
    if (len > max) {
      max = len;
      copy(longest, line);
    }
    // Following tradition, we will be ignoring the null character that marks
    // the end of every string. The standard library function strlen() also
    // ignores null characters.
    printf("Length: %d\n", len - 1);
    printf("Line: %s\n", line);
  }
  if (max > 0) {
    printf("%s", longest);
  }

  return 0;
}
...
hi
Length: 2
Line: hi

there this is an 
Length: 16
Line: there this is an

arbitrarily long string
Length: 23
Line: arbitrarily long string

moo 
Length: 3
Line: moo

arbitrarily long string