PROGRAM TWENTY-TWO
Write a program to count the number of words in a text file.
{ Program to count words in a text file. Adapted from C program found}
{ in Programming in C : S Kochan, pg 174 - }
program PROG22 (input, output, infile );
type oneline = packed array[1..81] of char;
{ a function to determine if a character is alphabetic }
function alphabetic ( ch : char ) : boolean;
begin
if ( ((ch >= 'a') AND (ch <= 'z')) OR ((ch >= 'A') AND (ch <= 'Z')) ) then
alphabetic := TRUE
else
alphabetic := FALSE
end;
{ a function to count the number of words in a string }
function count_words ( var line : oneline ) : integer;
var i, word_count : integer;
looking_for_word : boolean;
begin
looking_for_word := TRUE;
word_count := 0;
for i := 1 to 81 do
begin
if alphabetic( line[i] ) then
begin
if looking_for_word then
begin
word_count := word_count + 1;
looking_for_word := FALSE
end
end
else
looking_for_word := TRUE
end;
count_words := word_count
end;
var infile : text;
tline : oneline;
fname : string[15];
total,count : integer;
ch : char;
begin
total := 0;
writeln('Please enter name of input file to count');
readln (fname);
assign (infile, fname);
reset( infile);
while not eof(infile) do
begin
for count := 1 to 81 do
tline[count] := ' ';
count := 1;
while not eoln(infile) do
begin
read(infile, ch );
tline[count] := ch;
count := count + 1
end;
total := total + count_words( tline );
readln(infile) { read eoln character }
end;
writeln('There are ',total,' words in the text file.')
end.
Copyright B Brown/P Henry/CIT, 1988-1997. All rights reserved.