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

/* Write a Program to print the longest line input */

#include<stdio.h>
#define MAXLINE 1000

int mgetline(char line[],int lim);
void copy(char to[],char from[]);


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

    max =0;

    while((len=mgetline(line,MAXLINE)) > 0)
    {
        if(len > max)
        {
            max = len;
            copy(maxline,line);
        }
    }

    if(max>0)
        printf("%s",maxline);
}
    

int mgetline(char s[],int lim)
{
    int i,c;

    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;
}

void copy(char to[],char from[])
{
    int i;
    i=0;

    while((to[i]=from[i]) != '\0')
    ++i;
}
        
Run this

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.

Comments by Disqus