z d
z d

Reputation: 41

how do I save STL map to file C++

I am trying to safe data to file using map, but I don't know how. I want to save the student's name and age into the file and then when I look up a name of a student it should display their age.

#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();
}

Upvotes: 4

Views: 2948

Answers (2)

Lectral
Lectral

Reputation: 65

You need to improve your code. Add getters and setters to your student class because now there is no way to write to the map inside the class. For example add a method that let's you push your student info into private map member.

Then I recommend to learn about boost serialization: http://www.boost.org/doc/libs/1_52_0/libs/serialization/doc/index.html

If you want a simpler way then learn about std::fstream library.

Upvotes: -1

David Schwartz
David Schwartz

Reputation: 182769

Start by deciding on exactly how the data will be stored in the file at the byte level. For example, it could be:

  1. Each student occupies exactly one line in the file.

  2. Lines are separated by a single newline character.

  3. Each line consists of a quote, the student's name, a quote, a comma, and the student's age.

You then need to write code to output in that format and read in from that format. Note that this will break if the name contains a quote.

Upvotes: 2

Related Questions