1

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
PaulH
  • 7,759
  • 8
  • 66
  • 143

2 Answers2

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);
}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1

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);
}
Martin York
  • 257,169
  • 86
  • 333
  • 562