Witam. W programie tworzę obiekt a następnie umieszczam go na liście. Teraz chciałbym zapisać listę tych obiektów do pliku. W jaki sposób najprościej to zrobić? Ostatnio poznałem czym jest przeciążenie operatora, ale tym razem chciałbym to zrobić bez przeciążenia, ponieważ na pewno istnieje jakaś inna metoda i chciałbym ją poznać. Czytałem o serializacji, ale trohe za głupi jestem. Jest prostszy sposób ? To co nabazgrałem sam, nie działa.
#include<iostream>
#include <string>
#include <process.h>
#include <list>
#include <cstddef>
#include <fstream>
#include<cstdlib>
#include <sstream>
using namespace std;
class Player {
string name;
string surname;
string posOnThePitch;
public:
void enter_data() {
cout << "\nName: ";
cin >> name;
cout << "Surname: ";
cin >> surname;
cout << "Possition: ";
cin >> posOnThePitch;
}
string getFulName()
{
string temp;
temp = name + " " + surname + ", " + posOnThePitch;
return temp;
}
};
class Team {
list<Player>team;
public:
void add_player()
{
Player player;
player.enter_data();
team.push_back(player);
cout << "\n\n\n";
}
void display_list()
{
if (team.empty())
{
cout << "\n\nThe list is empty. Add player or open list from file.\n\n";
}
cout << "\n\n\n";
list<Player>::iterator it = team.begin();
int number=1;
while (it != team.end())
{
cout << number++ << ": " << it->getFulName()<<endl;
it++;
}
cout << "\n\n\n";
}
void save_to_file()
{
fstream file;
file.open("list.txt", ios::out);
list<Team>team;
list<Team>::iterator it = team.begin();
int number = 1;
while (it != team.end())
{
file << it->display_list();
it++;
}
file.close();
}
};
int main()
{
Team team;
char switchOption;
do {
cout << "1. Add player" << '\n';
cout << "2. Display list" << '\n';
cout << "3. Save to file" << '\n';
cout << "4. Read from file" << '\n';
cout << "5. Remove player from list" << '\n';
cout << "6. Exit" << '\n';
cin >> switchOption;
switch (switchOption) {
case '1'://1. Add player
{
team.add_player();
break;
}
case '2'://2. Display list
{
team.display_list();
break;
}
case '3'://3. Save to file
{///////////////////////////////////////////////////////////
team.save_to_file();
break;
}///////////////////////////////////////////////
case '4'://Open from file
{
//jjjj
}
break;
case '5':// 5. Remove player from list
{
cout << "working..\n";
break;
}
case '6':// 6.exit
{
cout << "Goodbye !\n";
break;
}
default:
{
cerr << "Jakis nieokreslony przypadek.\n";
}
}
} while (switchOption != '6');
system("pause");
}// main