コンマ区切りの文字列を const char* のベクトルに変換しようとしています。次のコードでは、予想される出力は
ABC_
DEF
HIJ
しかし、私は得る
HIJ
DEF
HIJ
どこが間違っていますか?
コード:
#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;
}
編集: 以下の回答を利用したソリューション: (PaulMcKenzie は、リストを使用してより適切なソリューションを提供しています。)
#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;
}