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
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.
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);