Problem Statement
Exercise 1-17: Write a program to print all input lines that are longer than 80 characters.Solution
We need to count number of character in a line, buffer entire line and print it. Lets read one character from stdin using getc and use variable len to count number of characters in the input. Since we need to buffer all characters to print line > 80, lets use array buf_line to do that.Using above information C code would like this.
#include <stdio.h> #define MAX_LINE 256 void print_line(int *p, int len) { int i = 0; while(i < len) printf("%c", p[i++]); printf("\n"); } int main() { int c, len = 0; int buf_line[MAX_LINE]; while((c = getc(stdin)) != EOF) { if(c == '\n') { if(len >= 80) { print_line(buf_line, len); } len = 0; }else { if(len < MAX_LINE) buf_line[len++] = c; } } }
No comments :
Post a Comment