Possible Duplicate:
How do I tokenize a string in C++?
Hello I was wondering how I would tokenize a std string with strtok
string line = "hello, world, bye";
char * pch = strtok(line.c_str(),",");
I get the following error
error: invalid conversion from ‘const char*’ to ‘char*’
error: initializing argument 1 of ‘char* strtok(char*, const char*)’
I'm looking for a quick and easy approach to this as I don't think it requires much time
I always use
getline
for such tasks.to find the next token, repeat
find_first_of
but start atpos + 1
.You can use
strtok
by doing&*line.begin()
to get a non-const pointer to thechar
buffer. I usually prefer to useboost::algorithm::split
though in C++.strtok
is a rather quirky, evil function that modifies its argument. This means that you can't use it directly on the contents of astd::string
, since there's no way to get a pointer to a mutable, zero-terminated character array from that class.You could work on a copy of the string's data:
or, for more of a C++ idiom, you could use a string-stream:
or find the comma more directly: