简体   繁体   中英

std::string constructor throws std::out_of_range exception

Using VS 2012.

I was making hangman. Anyway, I had a function to get a std::string that was the same length as the current word being guessed, but filled with underscores. (as in, blanks).

The function:

std::string getBlankWord(std::vector<std::string> words, int currentWordIndex)
{
    return std::string(words[currentWordIndex], '_');
}

The line it is called on:

currentGuessingString = getBlankWord(words, index);

words is an std::vector, index is an int. words.size() = 22, and index = 0, so I don't know how calling, in this case, words[0] could be the culprit. Anyway, something on this line throws std::out_of_range exception, but I cannot find it.

Thanks.

我觉得你真正想要的更像是:

return std::string(words[currentWordIndex].size(), '_');

Your problem appears because the constructor that ends up being called is the substring constructor (see here )

The first argument is easy to figure out, the second one however will be a char with the ascii value of '_' implicitly casted to a size_t and its' value is most likely bigger than the size of the string you are giving to the constructor which in turn causes your problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM