You can change the for condition to:
Code:
for (int i=0; i<s.size()-2;i++)
That'll stop it from running out of bounds.
find("and") will (if I understand correctly) keep finding the same "and" over and over again. You can pass it a place to start as the second parameter.
Code:
while(getline(infile, s))
{
size_t strpos = 0;
strpos = s.find("and"); // search from the start
while (strpos != string::npos)
{
count++;
strpos = s.find("and", strpos+1); // search the rest of the string
}
}
find() would return 0, or false, if it found an "and" at the start of the string, so I'm surprised that that was working for you.