如何从该文件中的不同行加载数据?

How do I load the data from separate lines in this file?

本文关键字:加载 数据 文件      更新时间:2023-10-16

我正试图将值从文件加载到一个名为Friend的类的动态数组中。Friend类有两个私有变量,一个字符串表示名称,一个Date类对象。我重载了输入操作符来调用这个函数,input for friend:

void Friend::input(std::istream& ins){
  char tmpname[50];
  bool x = false;
  std::cout << "Please enter a name: ";
  ins>>tmpname;
  std::string tmpstring(tmpname);
  name = tmpstring;
  ins.sync();
  std::cout << "nn" << "Please Enter a Birth date in MM/DD/YYYY format: ";
  ins.sync();
  ins >> bday;
  ins.sync();
  std::cout<<"nn";
}

的输入操作符也为Date类重载,该类有三个int类型,分别表示月、日和年。下面是代码:

// input operator, overloaded as a friend
istream& operator >>(istream& ins, Date& d){
   bool flag = false;
   string junk;
   ins>>d.month;
// if an invalid month is detected throw a bad_month
       if(d.month < 1 || d.month > 12){
                getline(ins,junk); // eat the rest of the line
                throw (bad_month(d.month));
        }
// if the read has failed because of eof exit funtion
  if(ins.eof()) return ins;
   if(ins.peek() == '/') ins.ignore();
       ins>>d.day;
// if an invalid day is detected throw a bad_day
        if(d.day < 1  || d.day > d.daysallowed[d.month]){
                getline(ins,junk); // eat the rest of the line
                throw (bad_day(d.month, d.day));
        }
  if(ins.eof()) return ins;
  if(ins.peek() == '/') ins.ignore();
   ins>>d.year;
   return ins;
}

在FBFriends类中,我有一个Friend类型的动态数组,我需要从开始加载的文件中加载已保存的姓名和出生日期。文件必须是这样的格式:

First Last
MM/DD/YYYY
First Last
MM/DD/YYYY
First Last
MM/DD/YYYY

我尝试的加载函数是:

void FBFriends::load(std::istream& ins){
  Friend f1;
  int i=0;
  while(ins >> f1){
    if(i % 2 == 0 && i != 0){insert(f1);};
    i++;
  }

  }

void FBFriends::insert(const Friend& f){
  if(used >= capacity){ resize();}
  for(int i = used; i>current_index; i--){
     data[i] = data[i - 1];
  }
  data[current_index] = f;
  used++;
}

我为长帖子道歉,我需要包括所有相关代码。加载函数将无效值插入日期函数,导致崩溃。我怎样才能正确地将这些值加载到Friend数组中呢?

由于name占用了一整行,所以使用getline读取name。替换

ins>>tmpname;
std::string tmpstring(tmpname);
name = tmpstring;

getline(ins, name);

FBFriends::load中,有:

while(ins >> f1){

只有当你有一个函数

std::istream& operator>>(std::istream& in, Friend& f) { ... }

我建议你删除

void Friend::input(std::istream& ins) { ... }

并替换为

std::istream& operator>>(std::istream& in, Friend& f) { ... }

还有,我不明白

的目的
if(i % 2 == 0 && i != 0){insert(f1);};

我相信你知道你在做什么。