The UNIX and Linux Forums  

Go Back   The UNIX and Linux Forums > Top Forums > High Level Programming
.
google unix.com




View Single Post in the UNIX and Linux Forums - Click on the Thread or Permalink to View Entire Thread -->
  #1 (permalink)  
Old 10-04-2008
sathishkmrv sathishkmrv is offline
Registered User
  
 

Join Date: Sep 2007
Posts: 6
How to use strtok twice in the same program?


Code:
       string str1(" 1 2 3 4 512543 ");
                 string str2;
                 if(str2.empty())
                        str2=str1;
                cout << "str2:" <<str2 <<endl;
                p1=strtok((char *)str1.c_str()," ");
                while(p1)
                {
                        v1.push_back(atoi(p1));
                cout << "val of p1 " << p1 << endl;
                 p1=strtok(NULL," ");
                }
                cout << "size of v1 " << v1.size() <<endl;
                p2=strtok((char *)str2.c_str()," ");
                cout << "str2:" <<str2 <<endl;
                while(p2)
                {
                        v2.push_back(atoi(p2));
                        cout << "val of p2 " << p2 <<endl;
                        p2=strtok(NULL," ");
                }

                cout << "size of v2" << v2.size() <<endl;

I get the following o/p.


Code:
str2: 1 2 3 4 512543 
val of p1 1
val of p1 2
val of p1 3
val of p1 4
val of p1 512543
size of v1 5
str2: 1234512543
val of p2 1
after tok p2  
size of v21

I want str2 also to be tokenized. But strtok after reaching NULL once it returns only NULL pointer everytime when it is accessed using NULL.

How can I tokenize str2 now?

Thanks