c++ - Vector of comma separated token to const char** -
i trying convert comma separated string vector of const char*. following code, expected output is
abc_ def hij
but get
hij def hij
where going wrong?
code:
#include <iostream> #include <boost/tokenizer.hpp> #include <vector> #include <string> using namespace std; int main() { string s("abc_,def,hij"); typedef boost::char_separator<char> char_separator; typedef boost::tokenizer<char_separator> tokenizer; char_separator comma(","); tokenizer token(s, comma); tokenizer::iterator it; vector<const char*> cstrings; for(it = token.begin(); != token.end(); it++) { //cout << (*it).c_str() << endl; cstrings.push_back((*it).c_str()); } std::vector<const char*>::iterator iv; for(iv = cstrings.begin(); iv != cstrings.end(); iv++) { cout << *iv << endl; } return 0; }
edit: solution of answers below: (paulmckenzie offers neater solution using lists.)
#include <iostream> #include <boost/tokenizer.hpp> #include <vector> #include <string> using namespace std; char* createcopy(std::string s, std::size_t buffersize) { char* value = new char[buffersize]; memcpy(value, s.c_str(), (buffersize - 1)); value[buffersize - 1] = 0; return value; } int main() { string s("abc_,def,hij"); typedef boost::char_separator<char> char_separator; typedef boost::tokenizer<char_separator> tokenizer; char_separator comma(","); tokenizer token(s, comma); tokenizer::iterator it; vector<const char*> cstrings; for(it = token.begin(); != token.end(); it++) { //cout << it->c_str() << endl; cstrings.push_back(createcopy(it->c_str(), (it->length() + 1))); } std::vector<const char*>::iterator iv; for(iv = cstrings.begin(); iv != cstrings.end(); iv++) { cout << *iv << endl; } //delete allocations new //... return 0; }
here's thing: boost::tokenizer::iterator
doesn't return ownership of copy of string, refernce internal copy.
for example, after running code get:
hij hij hij
the solution replace cstrings.push_back((*it).c_str())
1 of following:
char* c = new char[it->length() + 1]; c[it->length()] = 0; cstrings.push_back(c); std::strncpy(c, it->c_str(), it->length());
doesn't pretty, won't faster (at least if want use boost::tokenizer
.
other option totally replace boost::tokenizer
e.g. strtok
- example can found here: c split char array different variables
you can use boost::algorithm::string::split
, might need remap string
const char*
later on.
Comments
Post a Comment