【问题标题】:Loop enters infinite loop if cout is missing如果缺少 cout,则循环进入无限循环
【发布时间】:2013-05-31 08:06:55
【问题描述】:

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

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 &lt;&lt; found1 &lt;&lt; endl; 放在found1 = inString.find(frame1, found1); 行下方时,循环正确执行。但是,如果我没有 cout &lt;&lt; found1 &lt;&lt; endl; 它会进入无限循环...

有什么建议吗?谢谢!

【问题讨论】:

  • 该代码并没有像您声称的那样做。如果您不向我们展示有问题的代码,我们该如何解决?
  • 请阅读并思考sscce.org

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


【解决方案1】:

这是一个错误(并且使用了一个未初始化的变量):

while (stringPos < 1);

因为它相当于:

while (stringPos < 1) {}

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

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

【讨论】:

    【解决方案2】:

    您的程序具有未定义的行为,因为您试图在此处使用未初始化变量的值:

    while (stringPos < 1)
    //     ^^^^^^^^^
    //     This is uninitialized
    

    这里:

    found1 = inString.find(frame1, found1);
    //                             ^^^^^^
    //                             This is uninitialized
    

    此外,即使您的变量已初始化,您也有一个分号,可以使您的 while 循环成为无操作或无限循环 (as hmjd correctly points out in his answer)。

    【讨论】:

      【解决方案3】:

      我将从初始化 stringPos 和 found1 变量开始。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多