我正在尝试使用map将数据保存到文件中,但是我不知道该怎么做。 我想要将学生的姓名和年龄保存到文件中,并且当我查找一个学生的姓名时,应该显示他们的年龄。
#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();
}
map<string,int>
而不是map<int,string>
。通常情况下,名称比年龄更独特。 - Benjamin Lindley