{"content":{"id":553,"title":"K\u0026R Solutions - 1.17","body":"\u003cp\u003e\u003cb\u003eQ:\u003c/b\u003e Write a program to print all input lines that are longer than 80 characters.\u003c/p\u003e\r\n\u003cp\u003e\u003cb\u003eA:\u003c/b\u003e\u003c/p\u003e \r\n\u003cpre\u003e\u003ccode class=\"cpp\"\u003e/* This is really a simpler version of the longest-line program: that already\r\n * has most of what we need. */\r\n#include \u0026ltstdio.h\u0026gt\r\n#define MAXLINE 1000\r\n\r\nint get_a_line(char s[], int lim);\r\n\r\n\r\nint main(void)\r\n{\r\n int len;\r\n char line[MAXLINE];\r\n\r\n while ((len = get_a_line(line, MAXLINE)) \u003e 0) {\r\n if (len \u003e 80) {\r\n printf(\"%s\", line);\r\n }\r\n }\r\n\r\n return 0;\r\n}\r\n\r\nint get_a_line(char s[], int lim) \r\n{\r\n int c, i;\r\n\r\n for (i = 0; i \u003c lim-1 \u0026\u0026 (c=getchar()) != EOF \u0026\u0026 c != '\\n'; ++i) {\r\n s[i] = c;\r\n }\r\n if (c == '\\n') {\r\n s[i] = c;\r\n ++i;\r\n }\r\n s[i] = '\\0';\r\n \r\n return i;\r\n}\r\n\u003c/code\u003e\u003c/pre\u003e\r\n\u003cpre\u003e\u003ccode class=\"lisp\"\u003eThis is a short sentence, which will not be repeated.\r\nThis, however, is a very, very, very long sentence, which will be repeated back by the program. \r\nThis, however, is a very, very, very long sentence, which will be repeated back by the program.\r\n\u003c/code\u003e\u003c/pre\u003e","publication_date":"2019-03-18T00:00:00.000Z","created_at":"2019-02-15T21:16:49.000Z","updated_at":"2019-02-15T21:20:51.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.17

Q: Write a program to print all input lines that are longer than 80 characters.

A:

/* This is really a simpler version of the longest-line program: that already
 * has most of what we need. */
#include <stdio.h>
#define MAXLINE 1000

int get_a_line(char s[], int lim);


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

  while ((len = get_a_line(line, MAXLINE)) > 0) {
    if (len > 80) {
      printf("%s", line);
    }
  }

  return 0;
}

int get_a_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') {
    s[i] = c;
    ++i;
  }
  s[i] = '\0';
  
  return i;
}
This is a short sentence, which will not be repeated.
This, however, is a very, very, very long sentence, which will be repeated back by the program.     
This, however, is a very, very, very long sentence, which will be repeated back by the program.