0

所以我有了这个,如果我注释掉底部, from int count = 0;toreturn 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;
}
4

2 回答 2

2

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

于 2013-02-16T05:31:17.633 回答
2

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

@xymotech 的回答中指出的内容是正确的。尽管如果循环确实结束了,缓冲区将在代码结束之前被刷新。

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

于 2013-02-16T05:32:09.057 回答