c++ zapis i odczyt z pliku z wykorzystaniem klas.

0

Witam. Posiłkowałem się już różnymi stronami, na wiele sposobów próbowałem to zrobić, ale mam problem.
Zapis do pliku działa świetnie, ale nie mogę jakoś wyprostować wczytania. Co robię źle?


#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <fstream>
using namespace std;

class Director
{
public:
	Director(){};
	Director(string, string);
	Director(Director &);

	

	void setPersonal(string, string);
	void addMovie(string);
	int pos;
	void show();
	
//private:
	
	string firstName, lastName;
	string movie[5];

};

class Genre
{
public:
	Genre(string);
	Genre(Genre &);
	void addDirector(Director );
	void changeDirector(int, string, string);
	int pos;
	void show();

	void write(string x);
	void read(string x);

private:
	string name;
	Director director[5];

};


void Genre::write(string x)
{
	
	ofstream file(x, ios::in | ios::out | ios::app);

		file << name;
		file << "\n";
		for(int i=0; i<=4; i++)
		{
		file << director[i].firstName;
		file << "\n";
		file << director[i].lastName;
		file << "\n";
			for(int j=0; j<=4; j++)
			{
			file << director[i].movie[j];	
			file << "\n";
			}
			file << "\n";
		};

		file.close();
};


void Genre::read(string x)
{
	string trash;
	ifstream file(x, ios::in | ios::out | ios::app);
	
		getline(file, name);
		/
		for(int i=0; i<=4; i++)
		{
		getline(file, director[i].firstName);
		
		getline(file, director[i].lastName);
		
			for(int j=0; j<=4; j++)
			{
			getline(file, director[i].movie[j]);	
		
			}
			
		};
	
		file.close();


};
 
1

Nie wiem czy przyczyna leży w tym, ale co to za dziwne flagi?

ifstream file(x, ios::in | ios::out | ios::app);

ifstream ma domyślną dobrą flagę, nie trzeba nic kombinować.

A z innych rzeczy to:

Przekazuj do konstruktora kopiującego stałą referencję

Director(const Director&);

Przekazuj string przez stałą referencję zamiast je kopiować za każdym razem

void Genre::write(const string& x)

Skoro korzystasz z C++11, to możesz generować konstruktor w ten sposób:

Director() = default;

Niby trochę więcej znaków trzeba wklepać, ale jasno wyraża intencję programisty.

0

Trochę pogmatwany ten kod, bo próbowałem to na sporo sposobów, także bez tych "flag" i dalej nie działa.
Nazwę klasy odczytuje idealnie, ale nie mogę się dobrać do elementów Directora, i nie wiem w czym leży problem?
Z moich prób zmian wynika, że jakoś błędnie się do niego odwołuję?

2

Debuguj, zamiast próbować "a nuż z tym się uda". Visual Studio ma bardzo dobry debugger.

1 użytkowników online, w tym zalogowanych: 0, gości: 1