我有一项任务是为类(class)项目创建记录管理系统。添加记录时,我想首先将当前记录文件的内容读入 vector ,然后对文件执行添加,最后输出回记录文件。但是,我很难思考如何构建它。我目前正在使用动态数组来存储数据,但是当我尝试将其放入 vector 时,它不会让我这样做,因为它是一个指针。我觉得我完全错误地处理了这个问题,需要一些帮助。这是我的输入函数:
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);
}
}
}
最佳答案
我看到的问题:
您正在使用
while (inF)
来打破循环。参见 Why is iostream::eof inside a loop condition considered wrong? .您正在使用一个指针
stud
读取所有值并在vect
中多次存储同一个指针。首先,编译器应该产生一个错误。您不能添加指向对象 vector 的指针。不清楚为什么函数需要
stud
作为参数。您可以在函数中轻松使用本地对象。像这样:for (int index = 0; index < size; index++){ student stud; if ( !(inF >> first >> last >> middle) ) { // Deal with error. } stud.setName(first, last, middle); ... }
最好检查对
inF >> ...
的调用是否成功分配了任何内容,而不是假设它成功了。而不是:inF >> first >> last >> middle;
使用
if ( !(inF >> first >> last >> middle) ) { // Deal with error. }
我建议更改所有此类调用。
关于c++ - 将文件读入 vector ,我的输入函数有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33529343/