Exercise 1-17 (Print long lines, getline)
Chapter_1 Exercise_1-16 | Exercise_1-18 |
Exercise 1-17 K&R, p. 31
Exercise 1-17. Write a program to print all input lines that are longer than 80 characters.
prnln.c download
#include <stdio.h> // for getchar(), putchar(), printf(), EOF
#define LENGTH 80 // minimum input line length printed (without '\0')
int getLine(char line[], int maxline); // getline() is declared in stdio.h
// int getLine(char [], int); // alternative declaration
void prnln(char line[]); // print line
// void prnln(char []); // alternative declaration
// print lines longer that LENGTH characters (including '\0')
int main()
{
int len; // current line length
char line[LENGTH+1]; // current input line
// +1 for ending '\0'
while((len = getLine(line, LENGTH+1)) > 0)
{ // line containing only '\n' has length 1
if (len > LENGTH) // len >= (LENGTH+1)
{prnln(line);} // here line[] does not end with '\n' (or EOF)
}
return 0;
}
// getLine(): read a line into s[] up to LENGTH chars, return length or LENGTH+1
int getLine(char s[], int lim) // return 0 at EOF
{
int c = EOF; // initialize
int i;
// getchar() is only executed if (i < (lim-1)):
for (i = 0; i < (lim-1) && (c = getchar()) != EOF && c != '\n'; i++)
{ // from 0 to lim-2; s[lim-2]='\n', s[lim-1]='\0'
s[i] = c;
}
if (c == '\n') // i < (lim-1), getchar() executed
{
s[i] = c; // '\n'
i++;
}
s[i] = '\0'; // the null character ends a string
if (c != EOF && c != '\n') // i == (lim-1) > 0
{ // in main() we need a condition to call prnln(), len > LENGTH:
return (i+1); // (i+1) == lim (LENGTH+1)
}
// else return i;
return i; // max(i) == (lim-1)
}
// prnln(); print line[], ending with first '\n' or EOF
void prnln(char line[])
{
int c;
printf("%s", line); // line[] does not end with '\n'
while ((c = getchar()) != EOF && c != '\n')
{putchar(c);}
putchar('\n'); // line may end with '\n' or EOF
}
/*
gcc prnln.c -o prnln
./prnln // input from the keyboard
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
// Ctrl+D in Linux, Ctrl+Z then Enter in Windows (EOF)
./prnln < prnln.c // source file
// getLine(): read a line into s[] up to LENGTH chars, return length or LENGTH+1
12345678901234567890123456789012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890
./prnln < prnln // binary file
*/
Chapter_1 Exercise_1-16 | BACK_TO_TOP | Exercise_1-18 |
Comments
Post a Comment