So I have this, and if I comment out the bottom part, from int count = 0; to return 0; it will print, but in this case, nothing prints out. Even adding cout << "Test" in the beginning does nothing. It all compiles fine though.
#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;
}
Compile it with
g++ -g a.cppthen run it with gdb, you’ll find that it’s in an infinite loop.What is pointed out in @xymostech ‘s answer is correct though. Although if the loop does end, the buffer will be flushed before the code ends.
Your pattern is always found in the string and therefore the
text.find(search)never returnsstring::npos