I am trying to convert a comma separated string to vector of const char*. With the following code, by expected output is
ABC_
DEF
HIJ
but I get
HIJ
DEF
HIJ
Where am I 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(); it != 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 with help of answers below: (PaulMcKenzie offers a 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(); it != 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 by new
//...
return 0;
}