find doesn't find a string in a range?

string::find isn't working as I thought it should... here is the example, I'm looking for the word "class" on the same line as a key sequence buy using the string::find(string,start,n) signature. Why doesn't find find it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
  
#include<string>
#include<iostream>
using std::string;
using std::cerr;
using std::endl;


int main(int argc, char **argv)
{
  string blah(
    "some long\n"
    "and stupid\n"
    "class blah::impl\n"
    "more stupid\n"
    "long\n"
    "text is in\n there");

  string key("blah::");

  size_t pos=blah.find(key);
  size_t prevLine=blah.rfind("\n",pos);
  size_t nextLine=blah.find("\n",pos);

  cerr
    << "Key " << key << " found at pos " << pos << "." << endl
    << "Looking for word \"class\" on this line, which is between pos "
    << prevLine << " and " <<  nextLine << "." << endl
    << endl;

  if (blah.find("class",prevLine,nextLine-prevLine+1)!=string::npos)
    {
    cerr << "STL works like I think it should!!!!" << endl;
    }
  else
    {
    cerr
      << "Am I loosing my mind? The word \"class\" is in there, "
      << "but find doesn't find it!!! see:" << endl
      << blah.substr(prevLine,nextLine-prevLine+1) << endl
      << "What am I missing here?"
      << endl;
    }

  return 0;
}
 






From the reference:
n
Length of sequence of characters to search for.

that is not "Length of area where to search"
In your case it's 5
Last edited on
Topic archived. No new replies allowed.