[英]Saving a vector of Structs into a file and reading a vector of structs from a file in C++
所以我有一个名为 person 的结构,其中包含不同类型的变量(字符串、int、float、bool),我创建了这个结构的向量。 现在我想将这个向量保存到一个文件中,以便以后阅读。 我不知道怎么做(我是编程新手)
#include<iostream>
#include<vector>
#include<string>
using namespace std;
struct person {
string firstName;
string lastName;
int age;
string adress;
string id;
string phoneNumber;
float bodyTemperature;
bool backgroundDisease;
string backgroundDiseaseInfo;
string bloodType;
bool breathingStatus; // true for normal and false for unusual
bool cough;
};
int main()
{
vector<person> database;
}
为了保存和自定义对象,我强烈推荐 boost 序列化库,请参见此处。
但是,这是一个没有提升的解决方案。 自定义对象的读取和写入可以通过重载 stream 运算符operator<<
和operator>>
来完成,这允许您从 stream 写入和读取数据。
在下面的代码中ofstream(filename) out
定义了一个 output 文件流,因此如果它不存在,它会创建一个名为filename
的文件。 您可以 stream 到它通过out << p
。 同样ifstream(filename)
打开一个输入文件流。 下面的完整代码允许您保存和加载SimplePerson
数据。
#include<iostream>
#include<vector>
#include<string>
#include<fstream>
#include<sstream>
struct SimplePerson {
SimplePerson() = default;
SimplePerson(const std::string &f, const std::string &l)
:firstName(f), lastName(l) {}
std::string firstName;
std::string lastName;
};
std::ostream& operator<<(std::ostream &out, const SimplePerson &p)
{
out << p.firstName << ' ' << p.lastName;
return out;
}
std::istream& operator>>(std::istream &in, SimplePerson &p)
{
in >> p.firstName >> p.lastName;
return in;
}
void save(const std::vector<SimplePerson> &database, const std::string &filename)
{
std::ofstream out(filename);
if(out.is_open())
for(const auto &p : database)
{
out << p << '\n';
}
else
std::cout << "error opening file" << std::endl;
}
void load(std::vector<SimplePerson> &database, const std::string &filename)
{
std::ifstream in(filename);
std::string line;
SimplePerson p;
while(getline(in, line))
{
std::istringstream iss(line);
iss >> p;
database.push_back(p);
}
}
int main()
{
std::vector<SimplePerson> original = {SimplePerson{"a","b"},
SimplePerson{"c","d"}};
save(original,"database.txt");
std::vector<SimplePerson> restored;
load(restored,"database.txt");
for (auto& p : restored)
std::cout << p << std::endl;
return 0;
}
我也强烈建议你买一本好书并学习基础知识
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.