[英]how do I save STL map to file C++
我试图使用地图安全数据文件,但我不知道如何。 我想将学生的姓名和年龄保存到文件中,然后当我查找学生的姓名时,应该显示他们的年龄。
#include <iostream>
#include <map>
#include <fstream>
#include <string>
using namespace std;
class student {
private:
map<int, string> map;
public:
void students(string name, int age);
};
void students(string name, int age) {
if (age < 1) {
cout << "You must enter a positive number." << endl;
return;
}
}
void main() {
ofstream filemap;
filemap.open("map.txt");
int age;
string name;
cout << "Please enter the name : " << endl;
cin >> name;
cout << "Please enter the age : " << endl;
cin >> age;
// code to save map to file
filemap.close();
}
首先确定数据将如何在字节级别存储在文件中。 例如,它可能是:
每个学生只占用文件中的一行。
行由单个换行符分隔。
每行包括一个引号,学生的名字,一个引号,一个逗号和学生的年龄。
然后,您需要编写以该格式输出的代码并从该格式读入。 请注意,如果名称包含引号,则会中断。
您需要改进代码。 将getter和setter添加到学生班级,因为现在无法写入班级内的地图。 例如,添加一个方法,让您将学生信息推送到私有地图成员。
然后我建议学习一下boost序列化: http : //www.boost.org/doc/libs/1_52_0/libs/serialization/doc/index.html
如果你想要一个更简单的方法,那么了解std :: fstream库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.