gpt4 book ai didi

c++ - while (_index != string::npos) 似乎并没有停止循环

转载 作者:行者123 更新时间:2023-11-28 08:19:43 26 4
gpt4 key购买 nike

我的代码计算字符串 temp 中的空格,效果很好。在代码的后面,我有一个类似的循环,但没有按预期结束。

根据我的调试和一些研究,我确定 while 循环没有在应该停止的时候停止第二次,因此抛出异常(std::out_of_range )… 为什么?两个 while 循环的条件相同,所以它们的行为应该相同,对吧?也就是说,当 find() 没有找到空格时,它们都应该停止循环……

第一部分代码:

// Just find out how many spaces are in the temp string for now
// Find index (position in the string) of the first space in temp string
_index = temp.find( " " );

// Loop as long as there are still spaces in temp string
while (_index != string::npos) {
// Find the index of the next space
_index = temp.find(" ", _index + 1);

// Keep track of how many spaces are in temp string
count++;
}

稍后(不要介意我的调试代码穿插其中):

// If the amount of spaces is just right, i.e. there are exactly SIZE - 1 spaces
if (count == SIZE - 1) {
cout << "\n\n - Inside the if (count == SIZE - 1) block\n"
<< " - temp = \"" << temp << "\", temp's size = " << temp.length()
<< "\n\n";

// This time, we're removing the spaces from the temp string in order to
// be able to search it for any non-number characters
// Find index of the first space in the temp string
_index = temp.find(" ");

cout << " - The first temp.find(\" \") yields: " << _index << "\n\n";

// Loop as long as there are still spaces in temp string
while (_index != string::npos) {
cout << " - Right before temp.replace() in the loop\n"
<< " - _index = " << _index << "\n\n";

// Remove the space in temp string
temp.replace(_index, 1, "");

// find the index of the next space
_index = input.find(" ", _index + 1);
}
// …
}

最佳答案

在第二个循环中,您引用了一个变量 input 而不是 temp

_index = input.find( " ", _index + 1 );`

因此循环永远不会终止。您不会在第一个 while 循环中执行此操作。

关于c++ - while (_index != string::npos) 似乎并没有停止循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6296328/

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