esprit2009 Profil : Jeune recrue | bonjour,
j'ai réalisé au cours de mon mini projet cette classe le.h
Code :
- #include<iostream>
- #include<string>
- #include <fstream>
- using namespace std;
- class matiere
- {
- string m_nom;
- int m_cof;
- public:
- matiere():m_nom(" " ),m_cof(0){} ;
- matiere(string nom,int cof):m_nom(nom),m_cof(cof){};
- friend istream &operator>>(istream &,matiere & );
- friend ostream &operator<<(ostream &,matiere);
- void ecrire();
- bool rechercher();
- void affiche();
- void ajouter();
- void changer(matiere);
- int getmatiere();
- };
|
le .cpp
Code :
- #include "matiere.h"
- istream &operator>>(istream &in,matiere &mat)
- {
- in>>mat.m_nom;
- cout<<"\t";
- in>>mat.m_cof;
- return in;
- }
- ostream &operator<<(ostream &out, matiere mat)
- {
- out<<endl;
- out<<mat.m_nom;
- out<<"\t";
- out<<mat.m_cof<<endl;
- return out;
- }
- void matiere::ecrire()
- {
- ofstream fichier("../matier.txt",ios::app|fstream::out);
- fichier<<*this;
- fichier.close();
- }
- void matiere::affiche()
- {
- matiere mat;
- ifstream fichier("../matier.txt",fstream::in);
- string ligne ="";
- while(!fichier.eof())
- {
- getline(fichier,ligne);
- cout<<ligne;
- cout<<endl;
- }
- fichier.close();
- }
- bool matiere::rechercher()
- {
- matiere mats;
- bool existe = false;
- ifstream fichier("../matier.txt",ios::app);
- string ligne;
- while(getline( fichier, ligne))
- {
- fichier>>mats;
- if(m_nom==mats.m_nom)
- existe=true;
- }
- return existe;
- }
- void matiere::ajouter()
- {
- if(!(*this).rechercher())
- {
- ofstream fichier("../matier.txt",ios_base::app|ios::out);
- fichier<<*this;
- fichier.close();
- }
- else
- cout<<"existe";
- }
- void matiere::changer(matiere mte)
- {
- ifstream fichier("../matier.txt",fstream::in);
- ofstream fichier2("../matier_tmp.txt",fstream::out);
- matiere m,ms,mss;
- while(!fichier.eof())
- {
- fichier>>m;
- if(m.m_nom==(*this).m_nom)
- fichier2<<mte;
- else if(m.m_nom!=ms.m_nom)
- fichier2<<m;
- }
- fichier.close();
- fichier2.close();
- remove("../matier.txt" );
- rename("../matier_tmp.txt","../matier.txt" );
- }
- int matiere::getmatiere()
- {
- return m_cof;
- }
|
une fonction main pour tester les différents fonctions de la classe matiere
Code :
- #include "matiere.h"
- void main()
- {
- matiere mat;
- for(int i=0;i<3;i++)
- {
- cout<<"donner le nom de matiere et son coefficiant"<<endl;
- cin>>mat;
- mat.ecrire();
- }
- mat.affiche();
- matiere mats("C#",12);
- matiere mate("fr",0);
- if(mats.rechercher())
- cout<<"matiere existe"<<endl;
- else
- cout<<"not exist"<<endl;
- mate.changer(mats);
- cout<<endl<<"----------------------------------------------------"<<endl;
- mats.affiche();
- }
|
j'ai un problème dans la fonction changer() qui change l'objet qui a appelé cette fonction par l'objet passe en paramètre. le problème est que la dernière ligne est toujours écrit 2fois.
Merci d'avance pour votre aide.
|