Exercise 1-16
Revise the main routine of the longest-line program so it will correctly print the length of arbitrarily long input lines, and as much as possible of the text.
/* I do not think this is a better answer. I think i will
* give another answer later. And actually, the specification
* of this exercise is not very clear. */
#include <stdio.h>
#define MAXLINE 20
int getline(char s[], int lim);
void copy(char to[], char from[]);
int main(void)
{
char line[MAXLINE];
char longest[MAXLINE];
char temp[MAXLINE];
int len, max, prevmax, getmore;
max = prevmax = getmore = 0;
while((len = getline(line, MAXLINE)) > 0)
{
if(line[len - 1] != '/n') {
if(getmore == 0)
copy(temp, line);
prevmax += len;
if(max < prevmax)
max = prevmax;
getmore = 1;
}
else {
if(getmore == 1) {
if(max < prevmax + len) {
max = prevmax + len;
copy(longest, temp);
longest[MAXLINE - 2] = '/n';
}
getmore = 0;
}
else if(max < len) {
max = len;
copy(longest, line);
}
prevmax = 0;
}
}
if(max > 0) {
printf("%s", longest);
printf("len = %d/n", max);
}
return 0;
}
int getline(char s[], int lim)
{
int c, i;
for(i = 0;
i < lim - 1 && ((c = getchar()) != EOF && c != '/n');
++i)
s[i] = c;
if(c == '/n')
{
s[i] = c;
++i;
}
else if(c == EOF && i > 0)
{
/* gotta do something about no newline preceding EOF */
s[i] = '/n';
++i;
}
s[i] = '/0';
return i;
}
void copy(char to[], char from[])
{
int i;
i = 0;
while((to[i] = from[i]) != '/0')
++i;
}
Exercise 1-17
Write a program to print all input lines that are longer than 80 characters.
/*
* Write a program to print all input lines that are longer
* than 80 characters.
*/
#include <stdio.h>
#define MAXLINE 80
int main(void)
{
int c, i;
char line[MAXLINE + 2] = {0}; /* 2 more is for '/n' and '/0' */
i = 0;
while ((c = getchar()) != EOF) {
if (c != '/n') {
line[i++] = c;
if (i > MAXLINE) {
line[i] = '/0';
printf("%s", line);
while ((c = getchar()) != EOF && c != '/n') {
putchar(c);
}
if (c == '/n') {
putchar(c);
i = 0;
memset(line, 0, MAXLINE + 2);
continue;
}
if (c == EOF) {
break;
}
}
}
else {
if (i <= MAXLINE) {
i = 0;
memset(line, 0, MAXLINE + 2);
continue;
}
}
}
return 0;
}