2013-02-16 74 views
0

所以我有這個,如果我註釋掉底部,從int count = 0;return 0;它會打印,但在這種情況下,沒有打印出來。甚至在開始時加入cout << "Test"什麼都不做。它雖然編譯好。爲什麼這不打印任何東西

#include <iostream> 
#include <string> 
#include <cctype> 
using namespace std; 

int main() 
{ 
    string text = "Smith, where Jones had had \"had had\", had had \"had\". \"Had had\" had had the examiners' approval."; 

    string search = "had"; 

    int length = (int) text.length(); 

    for(int i = 0; i < length; i++) 
    { 
     text [i] = tolower(text [i]); 
    } 

    cout << text; 

    int count = 0; 
    for (int index = 0; (index = text.find(search)) != string::npos; index += search.length()) { 
     count++; 
     } 

    cout << "There are " << count << " occurences of \"" << search << "\".\n"; 
    return 0; 
} 
+2

你的最後一個for循環是一個無限循環,因爲'search'在'text'總能找到。 – Meysam 2013-02-16 05:28:26

回答

2

編譯它與g++ -g a.cpp然後用gdb運行它,你會發現它是在一個無限循環。

@xymostech的答案中指出的是正確的。儘管如果循環結束,緩衝區將在代碼結束之前刷新。

你的模式總是在字符串中發現的,因此text.find(search)不會返回string::npos

2

你的第一個循環很好,但是你的第二個循環被卡在索引19處,因爲你總是從文本的開頭搜索。

相關問題