Debug assertion failed error

So my program is exactly the same, I just change the hidden word to bacon and now whenever I run and type a random guess in I get this error

This error means you’re using an out-of-range index to access a string character.
It is a good practice to always check the index before using it, e.g.
if (0 <= i && i < myWord.length()) {
// It is safe to access myWord[i]
}

I’m not sure I really understand, is it like initializing a variable?

what I’ve noticed is that it’ll not crash when I put in 4 or more letter words, but the bulls & cows counter is messed up. it’ll return the correct number of bulls (correct letters) but not cows.

thanks

If you can copy or upload your code somewhere so we can have a look, then it’d be easier to figure what exactly is wrong with it.

inside Fbullcowgame.cpp the submitguess function should contain the problematic bit, or inside main.cpp, the getguess part. I’ve gotten a bit lost with it copying along but the issue is with cin input I think.

http://www.filedropper.com/section02_1

SubmitGuess inside FBullCowGame.cpp contains the problematic bit. But it can be prevented from PlayGame inside main.cpp as well (compare the length of Guess with hidden word’s length and warn user if it is of different length).
The fix in SubmitGuess is little tricky - the words’ lengths and indexes are mixed, see my corrections below:

FBullCowCount FBullCowGame::SubmitGuess(FString Guess)
{
	//increment turn number
	MyCurrentTry++;

	//setup a return variable
	FBullCowCount BullCowCount;

	//loop through all letters in the guess
	int32 HiddenWordLength = MyHiddenWord.length();
  //for (int32 MHWChar = 0; MHWChar < HiddenWordLength; MHWChar++) // OLD
  for (int32 GChar = 0; GChar < Guess.length(); GChar ++) // <== CORRECTED
	{
		//compare letters against the hidden word
        //for (int32 GChar = 0; GChar < HiddenWordLength; GChar++) // OLD
		for (int32 MHWChar = 0; MHWChar < HiddenWordLength; MHWChar ++) // <== CORRECTED
		{
			//if they match then
      if (Guess [GChar] == MyHiddenWord [MHWChar] ) 
			{
				if (MHWChar == GChar) 
				{ //if in same place
					BullCowCount.Bulls++; //increment bulls
				}
				else {
					BullCowCount.Cows++; //must be a cow

				}					
			}
		}
	}

	return BullCowCount;
}
1 Like

Thanks for the help, I just realised that he goes over this issue in the very next video (enumerations @ 1:21) if anyone has the same issue :smiley:

Privacy & Terms