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 ||.
/**
* Exercise 2.2
*
* 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[], const 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 line[], int lim) {
int i, c;
for (i = 0; i < lim - 1; ++i) {
c = getchar();
if (c == EOF)
break;
if (c == '\n')
break;
line[i] = c;
}
if (c == '\n') {
line[i] = c;
++i;
}
line[i] = '\0';
return i;
}
void copy(char to[], const char from[]) {
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
Explanation¶
We use _getline 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.