将 csv 字符串读入向量 C++

asjhdbashjdbasjhdbhjb

csv to vector 有很多选项,包括读取 csv 文件并将其所有数据添加到 c++中的vector 中,但是我想要一些高于或低于csv -> vector. 相反,我有一个 CURL 函数,它将 csv 数据加载到一个std::string格式为

col1,col2,col3
abc,2,ghi
jkl,2,pqr

其中,每行由\n. 如何将给定结构中的数据解析为std::vector<data>

数据在哪里看起来像

struct data
{
  std::string col1, col3;
  int col2;
};
维克多·古宾

如果它只是您需要在应用程序中创建的解析器,您可以构建一些简单的流式递归解析器,如下所示:

#include <cctype>
#include <cstring>
#include <vector>
#include <string>
#include <iostream>

struct data
{
  std::string col1;
  int col2;
  std::string col3;
};

std::ostream& operator<<(std::ostream& to,const data& d)
{
    to << d.col1 << ',';
    to << d.col2 << ',';
    to << d.col3;
}

static char* skip_spaces(const char* csv)
{
  constexpr const char* WHITESPACE = "\t\n\v\f\r ";
  return const_cast<char*>( csv + std::strspn(csv,WHITESPACE) );
}


static const char* parse_csv_line(const char* csv, data& to)
{
  char* b = skip_spaces(csv);
  char* e = std::strchr(b,',');
  to.col1 = std::string(b,e);
  b = skip_spaces(e+1);
  e = std::strchr(b,',');
  to.col2 = std::strtol(b,&e,10);
  b = skip_spaces(e+1);
  e = std::strchr(b,'\n');
  if(nullptr == e) {
    e = b + std::strlen(b);
  }
  to.col3 = std::string(b,e);
  return ('\0' == *e) ? nullptr : e + 1;
}

std::vector<data> parse_csv(const char* csv)
{
  std::vector<data> ret;
  // skip header
  csv = std::strchr(csv,'\n');
  while(nullptr !=  csv) {
    data next;
    csv = parse_csv_line(csv, next);
    ret.push_back( next );
  }
  return ret;
}


int main(int argc, const char** argv)
{
  const char* CSV = "col1,col2,col3,\r\nabc,2,ghi\r\njkl,2,pqr";
  std::vector<data> parsed = parse_csv(CSV);
  for(auto d: parsed) {
    std::cout << d << std::endl;
  }
  return 0;
}

如果您需要更复杂的东西,即处理错误等,请使用一些CSV 解析库

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章