c ++从文件中读取多行代码

时间:2017-01-02 19:27:38

标签: c++ string io delimiter

我有以下文本文件布局:

  

人:Eugene Sandoval; 26岁;男性   记者
  艺术家
  人:约翰娜吉布斯; 34;女
  马戏团工作人员   电影制片人
  银行职员

第一行有关于此人的一些信息,下一行是他或她以前的工作。

这是我上课的课程:

#pragma once

#include <string>
#include <vector>

class Person
{
public:
  Person() {};
  ~Person() {};

  std::string name;
  std::string age;
  std::string gender;

  std::vector<std::string> previousJobs;

  friend std::istream& operator >> (std::istream& is, Person& p)
  {
    std::string line;
    std::getline(is, line);
    std::istringstream iss(line);

    std::getline(iss, p.name, ';');
    std::getline(iss, p.age, ';');
    std::getline(iss, p.gender, ';');

    return is;
  }
};

主:

int main()
{
     std::vector<Person> people;
     std::ifstream input_file("Resources/data.txt");

     Person p

     while (input_file >> p)
     {
        people.push_back(p);
     }

     getchar();
     return 0;
}

到目前为止,我已成功阅读第一行到对象中。但我正在努力将以前的工作读入载体。

1 个答案:

答案 0 :(得分:0)

成功读取文件的第一行并使用istringstream解析后,您可以对其他行执行相同的操作。如果您确定单个文件包含有关一个人的信息,那么您可以自由使用:

while (![your_file].eof())
{
  previousJobs.push_back(getline(is,line));
}
相关问题