Saving tokens into variables

Hello all,

I am trying to tokenize some string sentences. I decided to tokenize one string sentence at a time and save each token to a variable.

I tried using "strcpy(characterArray, aCstring)" but it didn't work. According to cplusplus.com , strtok returns a pointer to an individual token. Here is my code:

char id[30];

string sentence;

getline (i, sentence); // i is the ifstream object reading from a file

char *cString = new char [sentence.length() + 1];

tokenPtr = strtok(cString, ",");

strcpy(id, tokenPtr); // <--- This line of code did not work




How do I save the token to a variable?
Thanks.
Hi

If you wanted to do this the easy way (as opposed to the C way) you could maybe use boost::tokenizer (http://www.boost.org/doc/libs/1_47_0/libs/tokenizer/introduc.htm), especially if you're (not too un)comfortable with iterators.

Also in your code, do you want to copy sentence into cString, because I don't think you're doing that - you've just allocated the memory for it but not actually copied anything. In fact I wouldn't use new at all but something like:

1
2
char cstring[ sentence.length() + 1 ];
strcpy( cstring, sentence.c_str() );



strcpy(id, tokenPtr); // <--- This line of code did not work
What is the problem? Be aware that if strtok() doesn't find the "," it returns NULL.

Anyway why do you use strtok()? You can easyly replace it with the better functions from string like find() and substr()
Topic archived. No new replies allowed.