Jul 2, 2016

K & R : Exercise 1.17 - print lines longer than 80 characters

K & R : Exercise 1.17 - print lines longer than 80 characters

Problem Statement:

Exercise 1-17: Write a program to print all input lines that are longer than 80 characters.


Solution:

We need to count number of charecter in a line, buffer entire line and print it. Lets read one charecter from stdin using getc and use variable len to count number of charecters in the input. Since we need to buffer all charecters to print line > 80, lets use array buf_line to do that. Using above information C code would like this.

#include <stdio.h>

#define MAX_LINE 256

void print_line(int *p, int len)
{
  int i = 0;
  while(i < len)
    printf("%c", p[i++]);
  printf("\n");
}

int main()
{
  int c, len = 0;
  int buf_line[MAX_LINE];

  while((c = getc(stdin)) != EOF) {
    if(c == '\n') {
      if(len >= 80) {
        print_line(buf_line, len);
      }
      len = 0;
    }else {
      if(len < MAX_LINE)
        buf_line[len++] = c;
    }
  }
}

Links

No comments :

Post a Comment