我有一个Visual Studio 2008 C ++项目,我希望能够获取存储在std :: stringstream中的逗号分隔值列表,并将它们放在这样的向量中:
struct Foo
{
std::string A;
std::string B;
std::string C;
}
typedef std::vector< Foo > FooList;
std::stringstream csv; // contains comma separated values
如果流包含“My,Mother,Eats,\ nDonuts,From,Menards”,那么结果将是:
{ { "My", "Mother", "Eats" },
{ "Donuts", "From", "Menards" } }
实现这一目标的最佳方法是什么?如果有办法指定字符串如何复制到向量,我正在考虑使用boost.split
。
FooList list;
boost::split( list, csv.str(), boost::is_any_of( "," ) );
我可以控制流数据,所以如果稍微改变格式会让事情变得更容易,我就可以做到。
答案 0 :(得分:4)
// Input
std::stringstream csv;
// Prepare variables
FooList v;
std::vector<string> tokens(3);
std::string line;
// Iterate over lines
while (std::getline(csv, tmp)) {
// Grab comma-delimited tokens
tokens.clear();
boost::split(tokens, tmp, boost::is_any_of(","));
// Verify line format
if (tokens.size() != 3)
throw "There weren't three entries in that line >.<";
// Create and store `Foo`
Foo f = { tokens[0], tokens[1], tokens[2] };
v.push_back(f);
}
答案 1 :(得分:1)
尝试:
std::stringstream csv;
FooList v;
std::string line;
while (std::getline(csv, tmp))
{
std::stringstream linestream(line);
Foo item;
std::getline(linestream, item.A, ',');
std::getline(linestream, item.B, ',');
std::getline(linestream, item.C, ',');
v.push_back(item);
}