Exercise 2.2 - Write getline without && and || operator

Question

For example, here is a loop from the input function getline that we wrote in Chapter 1:

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

Write a loop equivalent to the for loop above without using && or ||.

/* Write a loop equivalent for getline without using && and ||
   This program prints the longest line in the given inputs */

#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 ;++i) {
        c = getchar();
        if (c == EOF)
            break;
        if (c == '\n')
            break;
        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

We use mgetline instead of getline, so that our compiler does not get confused with the builtin getline function.

The crux of the program is this.

for(i=0; i < lim - 1 ;++i) {
        c = getchar();
        if (c == EOF)
                break;
        if (c == '\n')
                break;
        s[i] = c;
}

Here we removed c = getchar() from the loop condition testing and we enter the loop and then check for conditions like EOF and n. If we encounter those undesirable condition, we simply break out of the for loop.

This is equivalent to the for loop above in the question which uses && condition to check.

Comments by Disqus