“字符串下标超出范围";从字符数组更改为字符串时出错? [英] "String subscript out of range" error when changing from character array to string?
问题描述
我开始使用字符串代替字符数组,并且在将定义为5的字符数组之一更改为字符串时遇到错误.尝试运行程序时出现的错误是表达式:字符串下标超出范围".
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 error I get is "Expression: string subscript out of range" upon trying to run the program.
"newWord"最初是一个字符数组,但是将其更改为字符串后,出现此错误.我不明白是什么原因导致的,使用字符数组时程序运行良好.
"newWord" was originally a character array, but upon changing it to a string I'm getting this error. I don't understand what could be causing this, when using the character array the program performs fine.
int main() {
fstream inputFile;
fstream outputFile;
string newWord;
int i, k;
string word;
inputFile.open( "H:\\word.txt" );
outputFile.open( "H:\\newword.txt" );
if( inputFile )
{
while( getline( inputFile, word ) )
{
for( i = 0; i < (word.length()- 3); ++i )
{
for( k = 0; k < 4; ++k )
newWord[k] = word[i+k];
cout << newWord << endl;
outputFile << newWord << endl;
}
}
}
return 0;
}
推荐答案
newWord[k]
newWord
字符串的大小为零.未定义在 std :: string
末尾进行索引的行为.
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);
这篇关于“字符串下标超出范围";从字符数组更改为字符串时出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!