将文件读取到向量中,我的输入函数有什么问题?
reading file into vectors, what's wrong with my input function?
我有一项任务要为一个类项目创建一个记录管理系统。当添加记录时,我想首先将当前记录文件的内容读取到向量中,然后对文件进行添加,最后输出回记录文件。然而,我很难将我的思想集中在如何构建这一点上。我目前正在使用一个动态数组来存储数据,但当我试图将其放入向量中时,它不允许我,因为它是一个指针。我觉得我完全错了,需要一些帮助。这是我的输入功能:
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)
来打破循环。请参阅为什么循环条件中的iostream::eof被认为是错误的?。 -
您使用一个指针
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); ... }
-
最好检查对
inF >> ...
的调用是否成功分配了任何内容,而不要认为它成功了。代替:inF >> first >> last >> middle;
使用
if ( !(inF >> first >> last >> middle) ) { // Deal with error. }
我建议更改所有此类呼叫。
相关文章:
- 如果我更改函数输入,我的递归不起作用?
- 初始化与函数输入相关的全局数组
- 如何生成比用户使用 rand() 函数输入的数字大 5-10% 的数字?
- 将函数更改为具有设置函数输入变量的方法的类
- 如何避免将 const 和非 const 成员函数输入到模板中的代码重复
- 是否有一种方法可以避免标头文件中使用的constexpr函数输入全局范围,而无需额外的名称空间
- 迭代器作为C 中的函数输入
- 如何为作为雇员类的指针传入的构造函数输入数据
- 最小的函数输入和输出错误
- C++ 函数输入错误
- QComboBox 作为 QT 中的函数输入参数
- 函数输入之前的分割故障
- 如何在视觉工作室 2012年设置函数输入参数的颜色
- 函数输入变化
- 使用函数输入 1 个 int 和 1 个字符串数组并循环
- 将数组用于函数输入参数
- 如何在c++中将函数输入强制转换为智能指针
- 自定义检查器的覆盖率引用函数输入
- 为什么我不能使用两个scanf函数输入字母
- 犰狳cov函数输入