3

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.

5
  • 1
    Fascinating Commented Mar 18, 2013 at 22:11
  • 2
    I wasn't aware of the std::string(const std::string&, int) constructor O.o It totally exists though: en.cppreference.com/w/cpp/string/basic_string/basic_string Commented Mar 18, 2013 at 22:13
  • 2
    Also, getBlankWord should take the vector by const reference: const std::vector<std::string>& words, or else it will copy the whole array each time you call the function :( Commented Mar 18, 2013 at 22:14
  • Not sure what you mean by the fascinating part - it holds 22 strings, thus the size is 22? Also, yes, I thought of that, but I planned to optimize it after I was sure the code would stay in there (as is, you don't notice speed problems, but only 22 words) Commented Mar 18, 2013 at 22:19
  • Fascinating because I really expected that code to result in a compiler error, but it actually performs exactly how you described. Commented Mar 18, 2013 at 22:26

2 Answers 2

5

I think what you really want here is more like:

return std::string(words[currentWordIndex].size(), '_');
Sign up to request clarification or add additional context in comments.

7 Comments

And why was the out of bounds exception occurring?
@MooingDuck because '_' is 242 in ascii. It copies 242 characters from the passed string.
@PeterWood: ASCII only has 128 characters, and _ is #95. I can see several pages listing _ as 242 in some codepage, but I can't figure out which codepage that is.
@MooingDuck Sorry, my mistake. I was looking at extended ascii, it is indeed 95 in ascii printable codes.
@PeterWood: I'm still interested in your comment. I figured you meant extended ascii, and found this, but interestingly, that page claims the extension is code page 437, but when I look up that code page, it has at that position instead!
|
4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.