Ajouter un commentaire

jaafaresprit
ecrire et lire un fichier txt

bonjour,
je suis un étudiant en 1er année informatique cycle ingénieur.J'ai écri cette classe qui lit et écrit dans un fichier txt matiere
le .h

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

Le .ccp

#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|ios::out);
		fichier<<*this;
	fichier.close();
}

void matiere::affiche()
{
	matiere mat;
	ifstream fichier("../matier.txt",ios::in);
	string ligne ="";
	while(getline(fichier,ligne))
	{ 
		fichier>>mat;
		cout<<mat;
	}
	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 ajouter(matiere mat)
{
	if(!mat.rechercher())
	{
		ofstream fichier("../matier.txt",ios_base::app|ios::out);
	    fichier<<mat;
	    fichier.close();
	}
	else
		cout<<"existe";
}

et un main pour tester les fonctions de la classe matiere

#include "matiere.h"
void main()
{
	matiere mat;

		for(int i=0;i<2;i++)
		{
			cout<<"donner le nom de matiere et son coefficiant"<<endl;
		    cin>>mat;
			mat.ecrire();
		}
	
		mat.affiche();

		matiere mats("francais",12);

		if(mats.rechercher())
			cout<<"matiere existe"<<endl;
		else 
			cout<<"not exist"<<endl;

	
}

Mon problème est que lorsque je lis du fichier matiere et je l'affiche sur l'écran, la dernière ligne est affiché 2fois pour tant dans le fichier, elle est écrit un seul fois

Filtered HTML

Plain text

CAPTCHA
Cette question permet de vérifier que vous n'êtes pas un robot spammeur :-)
 Y   Y  BBBB    QQQ    FFFF  N   N 
Y Y B B Q Q F NN N
Y BBBB Q Q FFF N N N
Y B B Q QQ F N NN
Y BBBB QQQQ F N N
Q