Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ tokenize std string [duplicate]

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

like image 888
Daniel Del Core Avatar asked Sep 27 '12 17:09

Daniel Del Core


2 Answers

I always use getline for such tasks.

istringstream is(line);
string part;
while (getline(is, part, ','))
  cout << part << endl;
like image 159
PiotrNycz Avatar answered Sep 25 '22 11:09

PiotrNycz


std::string::size_type pos = line.find_first_of(',');
std::string token = line.substr(0, pos);

to find the next token, repeat find_first_of but start at pos + 1.

like image 22
Pete Becker Avatar answered Sep 26 '22 11:09

Pete Becker