ch1-Extern longest line (getline)

Chapter_1     Exercise_1-19 Exercise_1-20







extlong.c     K&R, p. 32-33         download


#include <stdio.h> // for getchar(), putchar(), printf(), EOF

#define MAXLINE 1000 // maximum input line size

int max; // maximum length seen so far
char line[MAXLINE]; // current input line
char longest[MAXLINE]; // longest line saved here

int getLine(void); // getline() is declared in stdio.h
void copy(void);

// print longest input line; specialized version
int main()
{
int len;
// extern int max;
// extern char longest[];

max = 0;
while((len = getLine()) > 0)
{
if (len > max)
{
max = len;
copy();
}
}

if (max > 0) // there was a line
{
printf("%s", longest);
if(longest[max-1] != '\n')
{putchar('\n');} // longest may not end with '\n'
}

return 0;
}

// getLine(): specialized version
int getLine(void)
{
int c = EOF, i;
// extern char line[];
// getchar() is only executed if (i < (MAXLINE-1))
for (i = 0; i < (MAXLINE-1) && (c = getchar()) != EOF && c != '\n'; i++)
{ // from 0 to MAXLINE-2; line[MAXLINE-2]='\n' or not, line[MAXLINE-1]='\0'
line[i] = c;
}

if (c == '\n') // i < (MAXLINE-1), getchar() executed
{
line[i] = c;
i++;
}
line[i] = '\0';

return i;
}

// copy(): specialized version
void copy(void)
{
int i;
// extern char line[], longest[];

i = 0;
while((longest[i] = line[i]) != '\0')
{i++;} // ends after copying '\0'
// for (i = 0; (longest[i] = line[i]) != '\0'; i++) {}
}
/*
gcc extlong.c -o extlong
./extlong // input from the keyboard
The sky is gray
A storm is coming
Rain fills the rivers // Enter, then Ctrl+D in Linux, Ctrl+Z+Enter in Windows (EOF)
Rain fills the rivers

./extlong < extlong.c // source file
Rain fills the rivers // Enter, then Ctrl+D in Linux, Ctrl+Z+Enter in Windows (EOF)

./extlong < extlong // binary file
*/









Chapter_1     Exercise_1-19 BACK_TO_TOP Exercise_1-20



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo