开发者

deserializing a csv stream to a vector of structures

I have a Visual Studio 2008 C++ project where I would like to be able to take a list of comma-separated values stored in a std::stringstream and put them in a vector like this:

struct Foo
{
    std::string A;
    std::string B;
    std::string C;
}

typedef std::vector< Foo > FooList; 

std::stringstream csv;  // contains comma separated values

Such that if the stream contained "My,Mother,Eats,\nDonuts,From,Menards", the resulting structure would be:

{ { "My", "Mother", "Eats" },
  { "Donuts", "From", "Menards" } }

What's the best way to accomplish this? I was looking at using boost.split if there is a way to specify how the string is copied to the vector.

FooList list;
boost::split( list, csv.str(), boost::is_any_of( "," ) );

I have control over the开发者_开发问答 stream data, so if formatting it slightly differently makes things easier, I can do that.


// 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);
}


Try:

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜