L-31 MCS 260 Wed 31 Oct 2001
Below is the complete version of the program we discussed in class.
/* L-31 MCS 260 Wed 31 Oct 2001 : processing of characters
The program below counts the number of occurrences of "the"
and "a" in a sequence of characters. It is a good exercise
to extends this program so that it also counts the an's.
Be careful that the program discounts "the" and "a" in the
middle of words. Thus, in a phrase like
he is a fan of the theater
the program counts only one "the" and only one "a".
The purpose of the program is to illustrate the use of static.
This keyword occurs three times in the program, with three
different meanings :
1) The counters for the number of occurrences of "a" and "the"
are to be known only to the processing of the characters
and to the final printing routine, and NOT in main.
They are "static external variables".
2) In processing a character, we use two separate functions
to deal with "a" and "the". This distinction is irrelevant
to main, so we do not include it in the list of prototypes.
Those two functions are "static functions".
3) Finally, inside the processing, we keep track of the previous
character read and keep an internal state to remember if we
are reading an "a", a "the" or anything else.
This local variables are "static local variables".
This program should be used with redirection, for example as
a.out < text */
#include<stdio.h>
void process ( int c );
/* processes the character c, with an update of the number of a's
and the's */
void print_counts ( void );
/* points the number of times the "a" and "the" occurred */
int main ( void )
{
int c;
while ((c = getchar()) != EOF)
process(c);
print_counts();
return 0;
}
static int a_cnt = 0; /* counts the number of a's */
static int the_cnt = 0; /* counts the number of the's */
static void process_a ( int c )
/* we update the a counter if the current character c is a space,
and the previous character was an 'a' preceded by a space;
we are careful to discount cases like aa */
{
static int previous = ' ';
static int have_a = 0;
if ((c == 'a') && isspace(previous))
have_a = 1;
else
{
if (have_a && isspace(c)) a_cnt++;
have_a = 0;
}
previous = c;
}
static void process_the ( int c )
{
static int previous = ' ';
static int have_the = 0;
if ((c == 't') && isspace(previous))
have_the = 1;
else if ((previous == 't') && (c == 'h'))
previous = 'h';
else if ((previous == 'h') && (c == 'e'))
previous = 'e';
else
{
if (have_the && isspace(c)) the_cnt++;
have_the = 0;
}
previous = c;
}
void process ( int c )
{
process_a(c);
process_the(c);
}
void print_counts( void )
{
printf("The number of a's read : %d\n", a_cnt);
printf("The number of the's read : %d\n", the_cnt);
}