3

考虑以下:

我定义了一个类:

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 技术会比这更有效/更容易阅读?

4

1 回答 1

1

我写了一个骨架版本,它应该与线基结构一起使用:

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;
}
于 2013-06-04T12:47:47.473 回答