#include <iostream>
#include <fstream>
#include <cstdlib>
using std::cout;
using std::endl;
using std::cin;
using std::ifstream;
using std::ostream;
using std::istream;
class Agenda
{
// Interfaz pública:
public:
inline unsigned int contarPersonas(void);
inline std::string getname(void) const
{
return name;
}
inline unsigned int getage(void) const
{
return age;
}
void ordenar(void);
void set(const std::string&, unsigned int&);
friend ostream& operator<<(ostream&, const Agenda&);
friend istream& operator>>(istream&, Agenda&);
private:
std::string name;
unsigned int age;
};
unsigned int Agenda::contarPersonas(void)
{
ifstream entrada("Agenda.txt", std::ios::in);
if(!entrada.good())
exit(EXIT_FAILURE);
unsigned int contador = 0;
while(!entrada.eof())
{
if(entrada.get() == '\n')
contador++;
}
entrada.close();
return contador;
}
void Agenda::ordenar(void)
{
if(contarPersonas() <= 1) // No hacer nada.
return;
std::string *names = new std::string[ contarPersonas() ];
ifstream entrada("Agenda.txt", std::ios::out);
if(!entrada.good())
{
std::cerr << "Error abriendo archivo.";
exit(1);
}
char temporal[100];
unsigned int i = 0;
while(!entrada.getline(temporal, 100).eof())
names[i++] = temporal;
entrada.close();
unsigned int max = contarPersonas();
std::ofstream salida("Agenda.txt", std::ios::out);
for(i = 0; i < max; i++)
for(unsigned int j = 0; j < max; j++)
if(names[i] < names[j])
{
std::string aux = names[i];
names[i] = names[j];
names[j] = aux;
}
// Volcar al archivo :
for(i = 0; i < max; i++)
salida << names[i] << endl;
salida.close();
delete[] names;
}
void Agenda::set(const std::string& name, unsigned int& age)
{
this->name = name;
this->age = age;
}
ostream& operator<<(ostream& salida, const Agenda& persona)
{
ifstream entrada("Agenda.txt", std::ios::in);
if(!entrada.good())
exit(1);
char temporal[100];
salida << endl;
while(!entrada.getline(temporal, 100).eof())
salida << temporal << endl;
entrada.close();
return salida;
}
istream& operator>>(istream& entrada, Agenda& persona)
{
cout << "Ingrese el nombre : ";
entrada.ignore();
getline(entrada, persona.name);
cout << "Ingrese la edad : ";
entrada >> persona.age;
//entrada >> persona.age;
return entrada;
}
int main(void)
{
unsigned int op;
do
{
cout << endl << "1.Ingresar una persona al archivo" << endl;
cout << "2.Ver todas las personas del archivo" << endl;
cout << "3.Ordenar" << endl;
cout << "4.Salir" << endl;
cin >> op;
Agenda persona;
if(op == 1)
{
cin >> persona;
std::ofstream file;
file.open("Agenda.txt", std::ios::app);
file << persona.getname() << ' ' << persona.getage() << endl;
file.close();
} else if (op == 2)
{
cout << persona;
cout << "\n\n->" << persona.contarPersonas() << " actualmente.\n";
} else if(op == 3)
{
persona.ordenar();
}
} while (op != 4);
return 0;
}