Fichiers & structure c++

Fermé
abdou22 - 10 mai 2015 à 15:26
kharchafi Messages postés 9 Date d'inscription jeudi 14 mai 2015 Statut Membre Dernière intervention 18 mai 2015 - 15 mai 2015 à 10:58
bonjour, je voulais savoir comment sauvegarder le contenu d'un fichier dans une structure de donnée, j'ai deja essayé avec ce code et ca marche pas(avion est une class qui contient une structure et j'ai deja surchargé l'operateur ">>" ) :
avion *b;
ifstream f;
f.open("lesavions.txt",ios::in);
// if (!f) cout<<"erreur fichier !"<<endl;
if (!f.is_open())
cout << "Impossible d'ouvrir le fichier en lecture !" << endl;
while (1)
{

if(f.eof())break;


b=new avion();

f>>*b ;
cout<<"--------------------------"<<endl;

tab1.push_back(b) ;
A voir également:

1 réponse

kharchafi Messages postés 9 Date d'inscription jeudi 14 mai 2015 Statut Membre Dernière intervention 18 mai 2015
15 mai 2015 à 10:58
Bonjour,
Vous trouverez ci-dessous le code complet :
#include<string.h>
#include<stdlib.h>
#include<iostream>
#include <fstream>
#include <vector>
using namespace std;

class avion
{
char immatriculation[6];
float poids;
public:
avion(char* =NULL, float =0);
friend istream& operator>>(istream&, avion&);
friend ostream & operator << (ostream &,const avion &);
};
avion::avion(char* im, float p)
{
if(im==NULL)
  • immatriculation = '\0';

else
strcpy(immatriculation,im);
poids = p;
}
istream & operator >> (istream &_cin,avion &a)
{
_cin >> a.immatriculation;
_cin >> a.poids;
return _cin;
}
ostream & operator << (ostream &_cout,const avion &a)
{
_cout << "Immatriculation : " << a.immatriculation;
_cout << "\tPoids : " << a.poids << endl;
return _cout;
}
int main()
{
vector<avion> tab;
avion a;
ifstream f("lesavions.txt");

if (!f)
{
cout << "Erreur : Impossible d'ouvrir le fichier";
exit(-1);
}
f >> a;
while(!f.eof())
{
tab.push_back(a);
f >> a;
}
f.close();

for(int i=0; i<tab.size();i++)
cout << tab[i];
return 0;
}

sachant que le fichier texte contient l'immatriculation et le poids par ligne. Exemple :
124 154.56
78952 522226.35
788889 47885.69
0