2013-02-16 135 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处,因为你总是从文本的开头搜索。