【问题标题】:Read in arrays from a files and store them into struct members从文件中读取数组并将它们存储到结构成员中
【发布时间】:2021-12-08 10:09:48
【问题描述】:

假设我有一个这样的结构:

struct Person
{
  string fName;
  string lName;
  int age;
};

我想读入这样的文件(ppl.log):

Glenallen Mixon 14
Bobson Dugnutt 41
Tim Sandaele 11

我将如何读取文件并存储它们? 这就是我所拥有的

int main() 
{
  Person p1, p2, p3;
  ifstream fin;
  fin.open("ppl.log");
  fin >> p1;
  fin >> p2;
  fin >> p3;

  return 0;
}

整行都读吗?还是我必须使用 getline()?

【问题讨论】:

    标签: c++ arrays struct file-io


    【解决方案1】:

    我建议重载operator>>:

    struct Person
    {
      string fName;
      string lName;
      int age;
    
      friend std::istream& operator>>(std::istream& input, Person& p);
    };
    
    std::istream& operator>>(std::istream& input, Person& p)
    {
        input >> p.fName;
        input >> p.lName;
        input >> p.age;
        input.ignore(10000, '\n');  // Align to next record.
        return input;
    }
    

    这允许你做这样的事情:

    std::vector<Person> database;
    Person p;
    //...
    while (fin >> p)
    {
        database.push_back(p);
    }
    

    您的字段以空格分隔,因此您无需使用getline。字符串的operator&gt;&gt; 将一直读取到空白字符为止。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-22
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 2015-07-01
      • 1970-01-01
      相关资源
      最近更新 更多