将文件读取到向量中,我的输入函数有什么问题?

reading file into vectors, what's wrong with my input function?

本文关键字:函数 输入 什么 问题 我的 读取 文件 向量      更新时间:2023-10-16

我有一项任务要为一个类项目创建一个记录管理系统。当添加记录时,我想首先将当前记录文件的内容读取到向量中,然后对文件进行添加,最后输出回记录文件。然而,我很难将我的思想集中在如何构建这一点上。我目前正在使用一个动态数组来存储数据,但当我试图将其放入向量中时,它不允许我,因为它是一个指针。我觉得我完全错了,需要一些帮助。这是我的输入功能:

 void student::input(istream& inF, student* stud, vector<student>& vect, int size)
{
    //local variables
    string first, middle, last, addressNum, addressStreet, 
        phone, gender, email, emContactFirst, emContactLast;
    int ID, age;
    string ph, emPhone;
    while (inF)
    {
        for (int index = 0; index < size; index++){
            inF >> first >> last >> middle;
            stud->setName(first, last, middle);
            inF >> ID;
            stud->setId(ID);
            inF >> age;
            stud->setAge(age);
            inF >> phone;
            stud->setPhone(phone);
            inF >> addressNum >> addressStreet;
            stud->setAddress(addressNum, addressStreet);
            inF >> gender;
            stud->setGender(gender);
            inF >> email;
            stud->setEmail(email);
            inF >> emPhone;
            stud->setEmPhone(emPhone);
            inF >> emContactFirst >> emContactLast;
            stud->setEmContact(emContactFirst, emContactLast);
            inF >> stud->gpa >> stud->hobbies >> stud->major
                >> stud->probation;
            if (inF.eof())
                break;
            else
            stud++;
            vect.push_back(stud);
        }
    }
}

我看到的问题:

  1. 您正在使用while (inF)来打破循环。请参阅为什么循环条件中的iostream::eof被认为是错误的?。

  2. 您使用一个指针stud读取所有值,并在vect中多次存储同一指针。首先,编译器应该产生一个错误。不能添加指向对象向量的指针。

    目前还不清楚为什么函数需要stud作为参数。您可以在函数中轻松地使用本地对象。像这样:

    for (int index = 0; index < size; index++){
       student stud;
       if ( !(inF >> first >> last >> middle) )
       {
          // Deal with error.
       }
       stud.setName(first, last, middle);
       ...
    }
    
  3. 最好检查对inF >> ...的调用是否成功分配了任何内容,而不要认为它成功了。代替:

    inF >> first >> last >> middle;
    

    使用

    if ( !(inF >> first >> last >> middle) )
    {
        // Deal with error.
    }
    

    我建议更改所有此类呼叫。