queries about find_first_not_of and find_first_of member functions

Hi,
I am trying to tokenize a string of numbers. I made the program run with some combinations and it works successfully. However, I am still confused as to exactly what values these member function returns. I read the description but not able to understand it.

Here is the program
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
48
49
#include<iostream>
#include<vector>
#include<string>
using namespace std;

void tokenize(const string& str,vector<string>& tokens, const string& delimiter)
{
  //string:: size_type lastPos = str.find_first_not_of(delimiter, 0);
  int lastPos = str.find_first_not_of(delimiter, 0);

  cout<<"last position is\t"<<lastPos<<endl;

  string:: size_type pos = str.find_first_of(delimiter, lastPos);
  cout<< "position is\t"<<pos<<endl;

  while(string::npos !=lastPos || string::npos != pos)
  {
    cout<<"enter into while loop\t";
    tokens.push_back(str.substr(lastPos, pos-lastPos));

     cout<<"token is\t"<<tokens[pos]<<endl;
    cout<<"pos-lastPos is\t"<<(pos-lastPos)<<endl;

    lastPos = str.find_first_not_of(delimiter, pos);
    pos = str.find_first_of(delimiter, lastPos);
  }

  return;
}

int main()
{
  vector<string> tokens;
  string numbers("10 60 30, 59, 55, 22, 40 90, 15");
  tokenize(numbers,tokens, ",");

  vector<string> :: iterator it;

  cout<<"Tokens contain:\t";

  it=tokens.begin();

  while(it !=tokens.end())
  {
    cout<<" "<<*it<<endl;
    it++;
  }
  return 0;
}


The output is

last position is        0  
position is     8
enter into while loop   pos-lastPos is  8
enter into while loop   pos-lastPos is  3
enter into while loop   pos-lastPos is  3
enter into while loop   pos-lastPos is  3
enter into while loop   pos-lastPos is  6
enter into while loop   pos-lastPos is  4294967267
Tokens contain:  10 60 30
  59
  55
  22
  40 90
  15



The first two lines,
lastPos is 0 //could somebody please explain what exactly it did. It basically searches for the absence of given character(",") in the string and returns the first occurance. so when it encounters a string "10 60 30, 59, 55, 22, 40 90, 15" it immediately searches for absence of "," from the first position, (which is before the first token (10 60 30) and returns 0? Not sure about it.

pos is 8. //now find_first_of searches for firstthe occurance of "," after lastPos (first position), so shouldn't it be pos=1? why does it return 8? I am not able to understand.

Thanks in advance.
Topic archived. No new replies allowed.