Exercise 1.16 - Print length of arbitrary long input line

Question

Revise the main routine of the longest-line program so it will correctly print the length of arbitrary long input lines, and as much as possible of the text.

Solution

/**
 * Exercise 1.16
 *
 * Write a program to print the length of an arbitrarily long input line 
 * and as much text as possible
 * 
 **/


#include <stdio.h>

/* The size of the output that we would like */
#define MAX 1000

/* define our functions*/
int getNewLine(char line[], int max);
void copy(char to[], char from[]);

int main(){

  int len, max;
  char line[MAX];
  char longest[MAX];

  max = 0;
  while((len = getNewLine(line, MAX)) > 0){

    if(len > max){

      max = len;
      copy(longest, line);

    }
    
  }
  
  if (max > 0){

    printf("length = %i, string=%s", max, longest);
    
  }

  return 0;

}

/* get a line in a character array */
int getNewLine(char arr[], int lim){

  int c, i;

  for(i=0; i < lim -1 && (c=getchar()) != EOF && c != '\n'; ++i){
   
    arr[i] = c;

  }
  if(c == '\n'){

    arr[i] = c;
    ++i;
    
  }
 
  else{

    /* Continue to count the length even if it is longer than the max */
    while((c=getchar()!=EOF) && c != '\n'){
      
      ++i;
      
    }

    if(c == '\n'){

      arr[i] = c;
      ++i;
    
    }

  }

  arr[i] = '\0';
  return i;

}

/* copy one character array to another */
void copy(char to[], char from[]){

  int i;

  i = 0;

  while((to[i] = from[i]) != '\0'){ 

    ++i;
    
  }

}

Explanation

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.

We keep track of each line and it’s length using a variable, max. If the length of the line is greater than max, then we copy that line into the maxline using a copy routine.

At the end of the program, whichever was the longest line that was copied in maxline array, we just print that.