如何从该文件中的不同行加载数据?
How do I load the data from separate lines in this file?
我正试图将值从文件加载到一个名为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);};
我相信你知道你在做什么。
相关文章:
- 使用ifstream从DAT文件加载数据
- SqlDataAdapter 未加载数据表 - C++
- C ,MySQL API加载数据本地
- 使用提升库在队列和堆栈数据结构上保存和加载数据时出错
- 使用 fstream 从文件加载数据
- 从文件加载数据
- 将错误处理添加到加载数据的函数(但有时还需要使用默认值)
- C#从文件加载数据并分类为数组
- 保存/加载C++数据时出错
- C++简体版链表,当我加载数据以创建链表并输入更多数据时,似乎存在差距
- 我无法加载数据文件,总是无法打开它
- 从C++模拟中保存和加载数据的有效方法
- 快板 5 加载数据文件
- 通过C++虚幻引擎改进加载数据
- 使用套接字从页面加载数据
- 创建缓冲区以加载数据时出错
- 使用 boost 序列化到磁盘后无法加载数据
- 从C++中的CSV文件读取和加载数据时出现问题
- 如何在运行时通过插件机制动态加载数据类型
- 保存和加载数据C++