So, i am going through the book 'Beginning C++ Through Game Programming'. I have reached the Hangman game and am trying to understand a few sections of code.
For the most part i feel like i understand it but would just like to check whether my understanding is sound or flawed.
These two sections of code in particular are my main issue
while (used.find(guess) != string::npos)
Does this mean, we are searching for 'used' using 'find' in the 'guess' and we do so until the end of the string, if we don't reach the end of the string then we have a match and we request a new character.
if (THE_WORD.find(guess) != string::npos)
Does this mean, we are searching for any of the letters in 'THE_WORD' using 'find' in 'guess' and we do so until the end of the string, if we don't reach the end of the string then we have a match and move forward.
string::find(string str); return the position of the first character of the matching "used" substring with "guess", and return std::string::npos (i.e -1) if there is no match.
if (THE_WORD.find(guess) != std::string::npos)
Same as above, you're searching for substring, not chars.
Without second argument, find search from the beginning of the string.
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.
I found the second link to be the most help.
Well you are about half right, but I believe backwards. You are searching the string "used" containing all the letters that are correct and have been used using "guess" as what to match to.
If a match is found you enter the while loop and arre asked to guess again until you enter a letter that is new.
Thank you for all of the above, that makes things a lot clearer
So basically we are finding the guess in used and finding the guess in the word
Regarding the != std::string::npos), does this mean until we reach the end of the 'used' string and 'the_word' string, or at least keep searching until we reach a match
npos basically means "not a position", which in this context means not found.
For the while loop, it means keep looping while a match is found, a match being found if they used that word already. At first loop the used would be empty, so the nothing would be found. Every time they try again, if the re-use a word, it is found, and the loop repeats.
In the other clause, the "THE_WORD" string, if not found, they failed the guess. Fashioned as != npos, that's "not - not found", which means found ;)