help with strtok function and pointers

May 24, 2011 at 5:29pm
I have a vector declared as:
1
2
3

vector<char *> records;


Then I have the following code to get a line from a file;

1
2
3
4
5
6
7
8
9

while(!archConfig.eof())
	  {
		 char buff[90];	 
		 archConfig.getline(buff, sizeof(buff));
		 records.push_back(buff);
	  }




Later in another method of my code I want to retrieve a specific element of
my vector and get the tokens from it.

1
2
3
4
5
6
7
8
9
int n = data;
  char *token;
  const char delimiters[] =" \t"; 
  *token = strtok(records.at(n), delimiters);
	     while (token!=NULL) 
		 {   
			 token = strtok(NULL, delimiters);
	      }


however the strtok function gives me an error: "A value of type char * can't be assigned to an entity of type char", It supposes that my vector stores data of type char*, but I am very confused with pointers, I've tried to use std::string instead but they I do know how to convert it to char * to use in strtok function. I want to keep it as simple as possible since i'll be processing many thousands of records. Thank you in advance for your help.
May 24, 2011 at 6:36pm
First of all, strtok modifies the first parameter by replacing the token with a null byte! Therefore, you can use strtok with C++! You want to use find() or find_first_of() instead.
May 24, 2011 at 8:45pm
You are doing this incorrectly. buff is a buffer in the stack. You are pushing a pointer to this buffer, but this buffer will disappear once it is out of scope. Use vector<std::string> instead. Also use strtok_s(), although that one might be Microsoft-specific?? See http://msdn.microsoft.com/en-us/library/ftsafwz3(VS.80).aspx.

As kooth stated, strtok() modifies the input string. If you want your strings untouched you must create copies. Besides, std::string::c_str() is const, so you shouldn't use this directly.
May 24, 2011 at 8:47pm
You should use a split function for this kind of thing. If you don't want to write your own, boost has one:
http://www.boost.org/doc/libs/1_46_1/doc/html/string_algo/usage.html#id2728530
Topic archived. No new replies allowed.