首页 文章

将csv流反序列化为结构向量

提问于
浏览
1

我有一个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( "," ) );

我可以控制流数据,所以如果稍微改变格式会使事情变得更容易,我就可以做到 .

2 回答

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

    尝试:

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

相关问题