class Hangman
{
private:
vector<string> dictionary; //stores all the words
vector<string> secretWord; //stores the secret word
vector<string> misses; //keeps record of wrong guesses
vector<string> displayVector; //Stores "_"
string originalWord; //stores a copy of secret word to display at the
end of game.
bool gameOver = false; //Flag to check if the player lost or
still in the game.
int totalAttempts;
public:
void selectRandWord();
};
//This is the function i am having problem in.
void Hangman::selectRandWord()
{
secretWord.clear();
//word is a basic string that stores a random word. lets say "Hello World".
string word;
srand(time(NULL));
int random = (rand() % dictionary.size()) 1;
//I store a random word from vector to word.
word = dictionary[random];
transform(word.begin(), word.end(), word.begin(), ::tolower);
originalWord = word;
for (int index = 0; index < word.length(); index )
{
//This line has the error: [Error] invalid user-defined conversion from 'char' to 'std::vectorstd::basic_string<char >::value_type&& {aka std::basic_string&&}' [-fpermissive]
//What I am trying to do is take each character from word(for example: "H") and push it back into the vector string secretWord.
secretWord.push_back(word[index]);
}
}
CodePudding user response:
Your secretWord
is now a vector<string>
type, so it's a collection of possibly many words, I'm not sure if that's what you really intend to have judging by the name. If it indeed is ok and you want to store every single character from word
as a separate string
in secretWord
, then you need to replace push_back
call with emplace_back
call as the other method actually does two things at a time: constructs a string
from the char
you pass to it and appends the string
to the end of the container, like this
secretWord.emplace_back(word[index]);
Mere push_back
fails because it needs to be provided with an object of the type your vector
stores, so you could also solve your problem by explicitly constructing a string
from your char
:
secretWord.push_back(string(word[index]));
I suggest you give a read to these: emplace back reference and push back reference if you're interested in copy/move details.