简体   繁体   English

std :: string构造函数抛出std :: out_of_range异常

[英]std::string constructor throws std::out_of_range exception

Using VS 2012. 使用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. 无论如何,我有一个函数来获取一个std :: string,其长度与猜测的当前单词的长度相同,但是用下划线填充。 (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. 单词是std :: vector,index是int。 words.size() = 22, and index = 0, so I don't know how calling, in this case, words[0] could be the culprit. words.size()= 22,index = 0,所以我不知道如何调用,在这种情况下,单词[0]可能是罪魁祸首。 Anyway, something on this line throws std::out_of_range exception, but I cannot find it. 无论如何,这一行上的某些内容会抛出std :: out_of_range异常,但我无法找到它。

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 第一个参数很容易弄明白,但第二个参数将是一个char,其ascii值为'_'隐式地转换为size_t,其'值很可能大于你给构造函数的字符串的大小这反过来会导致你的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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