ch1-words (Count chars, words, lines)

Chapter_1     Exercise_1-10 Exercise_1-11







words.c     K&R, p. 20         download


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

#define IN 1
#define OUT 0

// counts chars, words, and lines

int main()
{
int c;
long nc = 0;
int nw = 0;
int nl = 1; // last line in a file ends with "EOF," not '\n'
int state = OUT;

while ((c = getchar()) != EOF)
{
nc++;
if (c == ' ' || c == '\t') {state = OUT;}
else if (c == '\n')
{
nl++;
state = OUT;
}
else if (state == OUT) // not whitespace
{
state = IN;
nw++;
}
// else c is not whitespace and state == IN
}

printf("chars:\t%ld\n", nc);
printf("words:\t%d\n", nw);
printf("lines:\t%d\n", nl);
}
/*
gcc words.c -o words
./words // input from keyboard
Hello!
What's up?
// Ctrl^D in Linux, Ctrl^Z+Enter in Windows (EOF)
chars: 18
words: 3
lines: 3

./words < words.c // input from source file
chars: 967
words: 170
lines: 58

./words < words // input from binary file
chars: 16744
words: 64
lines: 7
*/





Note:  First, we check for spaces and tabs  (c == ' ' || c == '\t'), then for newlines  (c == '\n')  as there are generally more spaces than tabs and more tabs than newlines in any input.









Chapter_1     Exercise_1-10 BACK_TO_TOP Exercise_1-11



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo