为什么这不打印任何东西

时间:2013-02-16 05:19:56

标签: c++

所以我有这个,如果我注释掉底部,从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 个答案:

答案 0 :(得分:2)

你的第一个循环很好,但你的第二个循环卡在索引19,因为你总是从文本的开头搜索。

答案 1 :(得分:2)

g++ -g a.cpp编译然后用gdb运行它,你会发现它处于无限循环中。

@xymostech的答案中指出的是正确的。虽然如果循环结束,缓冲区将在代码结束前刷新。

您的模式始终在字符串中找到,因此text.find(search)永远不会返回string::npos