Exercise 1.17 - Print lines that are longer than 80 chars


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


/* Program to print the length of all input lines greater than 80 characters */

#define MAXLINE 1000
#define LIMIT 80

/* we call it ngetline, for new getline so that it does not conflict with system function getline */
int ngetline(char line[],int lim);

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

  while((len=ngetline(line,MAXLINE)) > 0)
    if( len > LIMIT )

  return 0;

int ngetline(char s[],int lim)
  int i,c;
  for(i=0;i<lim-1 &&(c=getchar())!=EOF && c!='\n';++i)

  if(c == '\n')
    s[i] = c;
    s[i] = '\0';

  return i;
Run this


A string in C is a character array which ends in \0. getline is a function in our program, which reads one character at a time using getchar and stores it in a character array called s[] and it returns the length of the array.

When an array is sent as argument to the function, like line[MAXLINE] is sent to getline function, the value is passed by reference, which means that any changes the function makes will be available to the main program.

getline returns the length of the line and in our main program, if the length is greater than 80 characters we print it.

Comments by Disqus