c++ - 如果 cout 丢失,循环进入无限循环

标签 c++ string while-loop infinite-loop endl

我遇到了一件很奇怪的事情。我遇到问题的代码是:

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) {}

如果这没有进入无限循环,它后面的代码将只执行一次。更正:

  • 初始化变量 stringPosfound1
  • 使用 size_t 类型作为 stringPosfound 作为 std::string::find()不返回 int,但返回 size_type(通常为 size_t)。
  • 使用std::string::npos而不是 -1 来测试未找到
  • 删除结尾的分号。

关于c++ - 如果 cout 丢失,循环进入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16926119/

相关文章:

c++ - Doxygen:使用 C++ 和 VHDL 的项目的无缝文档

string - 编写比较字符串函数

php - 必须有一个更简单的方法..从 mysql 中提取数据

c++ - 将 GoogleMock 与 Boost::Shared Pointers 一起使用时泄漏的模拟对象

c++ - 包含 vector 的指针列表的内存管理

C# '\n' 保存在与预期不同的字节中

mysql - 循环并使用存储的 MySql 选择

c - 在 C 中,我如何只接受某些字符串并继续要求用户输入直到输入有效输入?

c++ - 如何在 gdb 中将 C++ std::vector 的大小设为 "watch"?

c++ - 使用STL从字符串中删除重复字符