{ readingWords.p Started by Jeff Ondich on 9/30/96 Last modified on 1/6/97 This program reads all the words from a text file and prints them out on separate lines. Things to do: 1. Use Edit to create a small text file (a dozen or so words) called testdata.txt. Make sure to include plenty of punctuation, maybe some numbers, and a word or two containing an apostrophe. 2. Compile this program (gpc -o readingWords readingWords.p) and run it like so: readingWords < testdata.txt Does the program print out the words in your test data? Did the apostrophes come through okay? How about the numbers? 3. How does the "while" loop in this program work? What do you think "eof" stands for? 4. Now let's do part of your assignment for Monday by counting the words in your test data. Start by declaring a new variable "nWords" of type "integer". (You can put this declaration below the declaration of "theWord".) 5. To count the number of words in the input file, we need to do three things: (1) set nWords to 0 at the start of the program, (2) add 1 to nWords every time we read a new word, and (3) report nWords to the user. Give it a try. } program readingWords(input,output); var theWord : string(40); {==================================================== 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 ReadWord( theWord ); while not eof do begin writeln( theWord ); ReadWord( theWord ) end end.