I’m writing a hangman game. I’m having a logic fail, both with myself and my game logic. Char guess (the letter the person guessed) isn’t being added into the correct memory slot of the vector guessArray. Assume that word is an inputted word by the user.
I assume this would work if guessArray were a raw array. Is there some reason this isn’t working with a vector?
//assume that attempts is num of attempts left
void coutWord(int attempts, std::string word, char guess)
{
std::vector<char> guessArray(word.length());
//this is supposed to add the guess to the correct area of guessArray;
//It's not.
for (int i = 0; i < word.length(); i++) {
if (guess == word[i]) {
guessArray[i] = guess;
std::cout << " " << guessArray[i] << " ";
continue;
}
std::cout << " _ ";
}
std::cout << std::endl << std::endl;
}
EDIT: My objective with this code is to cout all the unguessed spaces AND the guessed spaces in the same for loop. I just need to “remember” previous guesses so that I get correct output. Given word = “Applesauce”:
Input: a
a _ _ _ _ _ a _ _ _
Input: p
a p p _ _ _ a _ _ _
etc.
A vector can be indexed with subscript notation
[], and it is stored in contiguous memory. It is an STL container so, like an array, you can have one of any type.A vector is automatically resized. An array is ‘statically’ sized, and cannot be easily resized (with the exception of a manual function called to realloc.) You can use a push_back function to handle this, and you can also .reserve() memory ahead of time to save on reallocation.
An array does not track it’s own size, whereas a vector has functions that can check this.
If you’re unsure of the size of a vector, just go ahead and use .push_back() to add items to handle the matter of automatically sizing. If you reserve a chunk of memory through resize() and then index into it, it’s easier to use as an array, but you lose some of the syntatic benefit of using it as a dynamically-sized object.