我遇到了一件很奇怪的事情。我遇到问题的代码是:
int stringPos;
int found1;
while (stringPos < 1);
{
//start searching inString for framen starting at foundn and record
found1 = inString.find(frame1, found1);
cout << found1 << endl;
//if return is a number, push back foundn to a vector
if (found1 != -1)
{
foundPositions.push_back(found1);
}
//if return is npos, then break the loop
else
{
stringPos=1;
}
//add 1 to foundn so that the search would continue from where the
//search ended last
found1+=1;
}
奇怪的是当我把cout << found1 << endl;
在 found1 = inString.find(frame1, found1);
行下方循环正确执行。但是,如果我没有 cout << found1 << endl;
它进入了一个无限循环...
有什么建议吗?谢谢!
最佳答案
这是一个错误(并使用了一个单元化变量):
while (stringPos < 1);
因为它等同于:
while (stringPos < 1) {}
如果这没有进入无限循环,它后面的代码将只执行一次。更正:
- 初始化变量
stringPos
和found1
。 - 使用
size_t
类型作为stringPos
和found
作为std::string::find()
不返回int
,但返回size_type
(通常为size_t
)。 - 使用
std::string::npos
而不是-1
来测试未找到。 - 删除结尾的分号。
关于c++ - 如果 cout 丢失,循环进入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16926119/