从逗号分隔的文本文件中创建有意义的数据向量的最佳方法是什么?

What is the best way to create a vector of meaningful data out of a comma delimited text file

本文关键字:最佳 数据 向量 方法 是什么 有意义 分隔 文本 文件 创建      更新时间:2023-10-16

考虑以下内容:

我已经定义了一个类:

class Human
{
public:
std::string Name;
std::string Age;
std::string Weight;
}

我有一个。txt文件定义:

Justin,22,170
Jack,99,210
Fred,12,95
etc...
目标是将此文本文件转换为std::vector

我现在的代码如下:

vector<Human> vh;
std::ifstream fin(path);
    std::string line;
    while(std::getline(fin,line))
    {
        std::stringstream   linestream(line);
        std::string         value;
        Human h;
        int IntSwitch = 0;
        while(getline(linestream,value,','))
        {
            ++IntSwitch;
            try{
            switch(IntSwitch)
            {
            case 1 :
                h.Name = value;
                break;
            case 2:
                h.Age = value;
                break;
            case 3:
                h.Weight = value;
                vh.push_back(h);
                break;

                }

            }
            catch(std::exception ex)
                {
                    std::cout << ex.what() << std::endl;
                }
        }

    }

现在我只是好奇是否有任何c++11技术或非c++11技术,将更有效/更容易阅读,然后这个?

我写了一个骨架版本,它应该与行基结构一起工作:

struct Human
{
  Human(const std::string& name, const std::string& age, const std::string& weight)
    : name_(name), age_(age), weight_(weight) { }
  std::string name_;
  std::string age_;
  std::string weight_;
};
class CSVParser
{
public:
  CSVParser(const std::string& file_name, std::vector<Human>& human) : file_name_(file_name) 
  {
    std::ifstream fs(file_name.c_str());
    std::string line;
    while(std::getline(fs, line))
    {
      human.push_back(ConstructHuman(line));
    }
  }
  Human ConstructHuman(const std::string& line);

private:
  std::string file_name_;
};
Human CSVParser::ConstructHuman(const std::string& line)
{
  std::vector<std::string> words;
  std::string word;
  std::stringstream ss(line);
  while(std::getline(ss, word, ','))
  {
   words.push_back(word);
  }
  return Human(words[0], words[1], words[2]);
}
int main()
{  
  std::vector<Human> human;
  CSVParser cp("./word.txt", human);
  return 0;
}