2013-06-04 44 views
0

我遇到了一些非常奇怪的事情。我有麻煩的代碼是:如果cout丟失,循環進入無限循環

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;它會進入無限循環...

有什麼建議嗎?謝謝!

+0

該代碼不會做你聲稱它做的。如果您不會向我們顯示問題的代碼,我們如何解決這個問題? –

+1

請閱讀並思考http://sscce.org/ –

回答

6

這是錯誤的(並且使用未初始化變量):

while (stringPos < 1); 

,因爲它等同於:

while (stringPos < 1) {} 

如果這沒有進入無限循環的代碼之後它只會執行一次。若要更正:

  • 初始化變量stringPosfound1。爲stringPosfound作爲std::string::find()
  • 使用類型size_t不返回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)。

0

我會從初始化stringPos和found1變量開始。