For everybody who have a problem with "String subscript out of range"

Maybe it will be helpful for someone who has the exception “String subscript out of range”.
Upgrade for loop (4th line here) in SubmitGuess method with additional condition ‘&& GChar < Guess.length()’ to avoid that exception:

 for (int32 MHWChar = 0; MHWChar < HiddenWordLength; MHWChar++)
    	{
    		// compare letters against the hidden word
    	>>>>for (int32 GChar = 0; GChar < HiddenWordLength && GChar < Guess.length(); GChar++)
    		{
    			// if they match
    			if (Guess[GChar] == MyHiddenWord[MHWChar])
    			{
    				// if they're in the same place
    				if (GChar == MHWChar)
    				{
    					// incriment bulls
    					BullCowCount.Bulls++;
    				}
    				else
    				{
    					// incriment cows
    					BullCowCount.Cows++;
    				}	
    			}				
    		}
    	}
2 Likes

Hi

Thanks for the help, but I really would like to know why that is happening with me and that doesn’t happen to the teacher? its a little bit strange.

Hi,
It hapens not only with you. The teacher has this problem too, if you look closely at the lectures from 37 till 41, the error window appears periodically, but he does not focus on this until it is corrected.

The problem is that we do not check the Guess word from the user to the right length and use length of hidden word instead. We continue to increase the index which thus goes out from the Guess string range and throws an exception.
Ben correct it in the switch statement lesson, but before I have found it I was annoying with this error :slight_smile: and dicided to find the decision before they help me.

1 Like

Privacy & Terms