gpt4 book ai didi

c++ - 从字符数组转换为字符串时出现"String subscript out of range"错误?

转载 作者:行者123 更新时间:2023-11-30 02:56:55 27 4
gpt4 key购买 nike

我开始使用字符串代替字符数组,当我将一个定义为 5 大小的字符数组更改为字符串时遇到错误。我在尝试运行程序时得到的错误是“表达式:字符串下标超出范围”。

“newWord”最初是一个字符数组,但在将其更改为字符串后出现此错误。我不明白是什么原因导致的,当使用字符数组时程序运行良好。

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 末尾的索引行为。

您可能需要调整字符串的大小,因此:

newWord.resize(5);

关于c++ - 从字符数组转换为字符串时出现"String subscript out of range"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15102779/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com