“String subscript out of range” error when changing from character array to string?

后端 未结 2 2029
孤街浪徒
孤街浪徒 2021-01-16 14:56

I\'m starting to use strings in place of character arrays and am encountering an error when I change one of my character arrays defined with a size of 5 to a string. The err

相关标签:
2条回答
  • 2021-01-16 15:24

    The error is because newWord[k] = word[i+k]; does not allocate a space for the string in newWord. The string length is 0, and it is undefined behaviour to do this. Use .append instead.

    From cplusplus.com:

    If pos is not greater than the string length, the function never throws exceptions (no-throw guarantee).Otherwise, it causes undefined behavior.

    In the case of newWord[k], pos is k.

    This is easy to avoid by using the append function in the string lib.

    From cplusplus.com, again:

    string& append (const string& str); //Appends a copy of str.

    0 讨论(0)
  • 2021-01-16 15:26
    newWord[k]
    

    The size of the newWord string is zero. The behavior of indexing beyond the end of a std::string is not defined.

    You may need to resize the string, thus:

    newWord.resize(5);
    
    0 讨论(0)
提交回复
热议问题