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

时间:2013-03-18 22:08:30

标签: c++ exception stdstring

使用VS 2012。

我正在制作刽子手。无论如何,我有一个函数来获取一个std :: string,其长度与猜测的当前单词的长度相同,但是用下划线填充。 (如,空白)。

功能:

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

调用它的行:

currentGuessingString = getBlankWord(words, index);

单词是std :: vector,index是int。 words.size()= 22,index = 0,所以我不知道如何调用,在这种情况下,单词[0]可能是罪魁祸首。无论如何,这一行上的某些内容会抛出std :: out_of_range异常,但我找不到它。

感谢。

2 个答案:

答案 0 :(得分:5)

我认为你真正想要的更像是:

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

答案 1 :(得分:4)

出现问题是因为最终被调用的构造函数是子字符串构造函数(请参阅here

第一个参数很容易弄明白,但第二个参数将是一个字母,其中ascii值为'_',隐式地转换为size_t,其'值很可能大于您给出的字符串的大小构造函数反过来导致你的问题

相关问题