Managing Arrays and Strings 425
13
Enter a string: this code first appeared in C++ Report
Got this word: this
Got this word: code
Got this word: first
Got this word: appeared
Got this word: in
Got this word: C
Got this word: Report
This program allows the user to enter in a sentence. The program then breaks out
each word (each set of alphanumeric characters) of the sentence. On line 15 is
the prompt asking the user to enter a string—basically a sentence. This is fed to a
method called GetWord()on line 18, along with a buffer to hold the first word and an
integer variable called WordOffset, which is initialized on line 13 to zero.
GetWord()returns each word from the string until the end of the string is reached. As
words are returned from GetWord(), they are printed on line 20 until GetWord()returns
false.
Each call to GetWord()causes a jump to line 26. On line 28, a check is done to see if the
value of string[wordOffset])is zero. This will be true if you are at or past the end of
the string, at which time GetWord()will return false. cin.GetLine()makes sure the
string entered is terminated with a null—that is, that it ends with a zero valued character
‘\0’;.
On line 31, two character pointers,p1and p2, are declared, and on line 32, they are set to
point into string offset by wordOffset. Initially,wordOffsetis zero, so they point to the
beginning of the string.
Lines 35 and 36 tick through the string, pushing p1to the first alphanumeric character.
Lines 39 and 40 ensure that an alphanumeric character is found. If not,falseis returned.
p1now points to the start of the next word, and line 44 sets p2to point to the same
position.
Lines 47 and 48 then cause p2to march through the word, stopping at the first nonal-
phanumeric character. p2is now pointing to the end of the word that p1points to the
beginning of. By subtracting p1from p2on line 53 and casting the result to an integer,
you are able to establish the length of the word. That word is then copied into the buffer
wordusing a string-copying method from the Standard Library, passing in as the starting
point p1and as the length the difference that you’ve established.
On line 59, a null value is appended to mark the end of the word. p2is then incremented
to point to the beginning of the next word, and the offset of that word is pushed into the
integer reference wordOffset. Finally,trueis returned to indicate that a word has been
found.
OUTPUT
ANALYSIS