{ readingWords.p Started by Jeff Ondich on 9/30/96 Last modified on 4/4/97 This program counts all the words in the input. Run it like so: readingWords < inputFile (assuming readingWords is the name you give the executable, and inputFile is the name of your input file). } program readingWords(input,output); var theWord : string(40); numberOfWords : integer; {==================================================== ReadWord reads the next "word" from standard input (i.e. the keyboard, or the input file specified by "< file" at the Unix command line), returning it via the variable parameter "word". Here, a word consists of a block of contiguous letters and/or apostrophes. Note that ReadWord will read past eoln when it is searching for the next word. We'll discuss this rather complicated code in class sometime in the next few weeks. ====================================================} procedure ReadWord( var word : string ); const apostrophe = chr(39); {The apostrophe character has ASCII value 39} type stateType = (beforeWord,duringWord,done); {See pages 198-200 of Abernethy & Allen to see what this is about.} var ch : char; state : stateType; function IsAlpha( c : char ) : boolean; begin IsAlpha := ((c >= 'a') and (c <= 'z')) or ((c >= 'A') and (c <= 'Z')); end; begin word := ''; state := beforeWord; while state <> done do begin if eof then state := done else if eoln then begin if state = beforeWord then readln else state := done end else begin read( ch ); if (ch = apostrophe) or (IsAlpha(ch)) then begin word := word + ch; state := duringWord end else if state = duringWord then state := done end end end; {end of ReadWord} {========================================================= Main Program =========================================================} begin numberOfWords := 0; ReadWord( theWord ); while not eof do begin numberOfWords := numberOfWords + 1; {You don't have to print each word, of course.} {writeln( theWord );} ReadWord( theWord ) end; writeln( 'There are ', numberOfWords, ' words.' ) end.