1.5.3 Line Counting¶
Program¶
#include <stdio.h>
static const char *_input = "line one\nline two\n";
static int _pos = 0;
#define getchar() (_input[_pos] ? (int)(unsigned char)_input[_pos++] : EOF)
/* count lines in input */
int main() {
int c, nl;
nl = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++nl;
printf("%d\n", nl);
}
Explanation¶
This Program counts input lines. The program does that counting by setting a variable nl to 0 in the beginning. As the program one character at a time in the while loop ((c = getchar()) != EOF) till the EOF. If the character is newline character ‘n’ the number of lines variable is incremented, ++nl. At the end, the number of lines, nl, is printed.
This document was updated on 25 May of 26
