Re: probable mistake in IDL manual [message #10380] |
Fri, 28 November 1997 00:00 |
davidf
Messages: 2866 Registered: September 1996
|
Senior Member |
|
|
Saeid Zoonematkermani (szoonem@astro.sunysb.edu) is
puzzled when he writes:
> I was reading "Building IDL Applications" manual (version 5) and noticed
> the procedure on p. 76 which is supposed to count the number of times that
> the word "dog" appears in the string "dog cat duck rabbit dog cat dog";
>
> ------
> pro Animals
> animals = 'dog cat duck rabbit dog cat dog'
> i = 0
> cnt = 0
> while (i ne -1) do begin
> i = strpos(animals,'dog', i)
> if (i ne -1) then cnt = cnt + 1
> endwhile
> print, 'Found ',cnt, "occurances of 'dog'"
> end
> ------
>
> When I read it, it struck me as being wrong. I tested it later and it
> seems to have gone into an infinite loop (as I suspected it would). Is it
> some thing VERY obvious that I am missing or is it simply wrong?
This reminds me of the kind of code I often write on this
newsgroup. The kind where just after you hit the 'SEND'
button, you think, "Ho boy, THAT code ain't gonna work!"
This code is obviously (well, after you study it for 10
minutes, like I did) wrong. Since the first occurrence of
the string 'dog' occurs at position 0, you are going to
be finding that particular string for a LONG time. :-)
The code *should* look like this:
pro Animals
animals = 'dog cat duck rabbit dog cat dog'
I = 0
cnt = 0
while (I ne -1) do begin
I = strpos(animals,'dog', I)
print, I
if (I ne -1) then BEGIN
I = I + 1 ; <----Fix is here!
cnt = cnt + 1
endif
endwhile
print, 'Found ',cnt, " occurances of 'dog'"
end
Cheers,
David
P.S. Take my word for it, it is really hard to get all the
code in a book correct. It is better to think of these
odd occurances and typos as that damn coyote at work again
and try to learn from them, as you are. :-)
-----------------------------------------------------------
David Fanning, Ph.D.
Fanning Software Consulting
E-Mail: davidf@dfanning.com
Phone: 970-221-0438
Coyote's Guide to IDL Programming: http://www.dfanning.com/
|
|
|