How to add file to c ++ program, with classes?

0

How to connect a text file (not binary), that stores data entered by the user in c ++, in this simple example:

#include <iostream>
#include <string>
#include <conio.h>
#include <stdio.h>
using namespace std;

class persona{
private:
 char nombre[40], apellido[40], cedula[40];
public:
 void registrar()
  {
    cout<<"Ingrese el nombre"<<endl;
    cin>>nombre;
    cout<<"Ingrese el apellido"<<endl;
    cin>>apellido;
    cout<<"Ingrese la cedula"<<endl;
    cin>>cedula;
  }
void mostrar()
 {
    cout<<"Los datos registrados son los siguientes: "<<endl;
    cout<<"Nombre: "<<nombre<<endl;
    getch();
    cout<<"Apellido: "<<apellido<<endl;
    getch();
    cout<<"Cedula: "<<cedula<<endl;
    getch();
 }
};
int main(int argc, char const *argv[])
{
 persona per1;
 per1.registrar();
 per1.mostrar();
 return 0;
}

Your response would be very helpful !! : D

    
asked by Cookie Rabbit 24.12.2016 в 15:25
source

3 answers

1

If you are using C ++ the most natural thing is to use the fstream library to manage the files and replace the character arrays by string, unless a fixed character size is mandatory.

Personally I do not recommend combining the logic of the program with the "Key Objects" in this case the Person class should only handle the data of the person in turn and not the registration or filling the latter should be done in another section of the program.

A possible implementation of the Persona class would be like this.

class Persona
{
private:
    string nombre;
    string apellido;
    string cedula;

public:
    Persona(const string& nombre, const string& apellido, const string& cedula)
    {
        this->nombre=nombre;
        this->apellido=apellido;
        this->cedula=cedula;
    }
    //Implementacion
    string getNombre()
    {
        return this->nombre;
    }
    string getApellido()
    {
        return this->apellido;
    }
    string getCedula()
    {
        return this->cedula;
    }
};

Then you could create an Agenda class, I do not know if in your case it's one but it's an idea you could handle the data of the people. Well in my case I create a class called Agenda where to manage people's records and will act as a kind of database, in which new records can be added or consult existing ones.

 class Agenda
{
private:
    fstream file;
    vector<string> split(const string& source,char token);
    bool fileExists(const string& ruta);

public:
    Agenda(const string& ruta);
    void agregar(Persona& persona);
    void agregarTodas(const vector<Persona>& personas);
    vector<Persona> leerTodo();
    ~Agenda();//Destructor de la clase
};

Agenda::Agenda(const string& ruta)
{
    if(fileExists(ruta))
    {
        file.open(ruta.c_str(),fstream::in | fstream::out | fstream::app);
    }
    else
    {
        file.open(ruta.c_str(),fstream::in | fstream::out | fstream::trunc);
    }
}

vector<string> Agenda::split(const string& source,char token)
{
    std::string sentence="";
    vector<string> result;

    for(char c :source)
    {
        if(c==token)
        {
            result.push_back(sentence);
            sentence="";
            continue;
        }
        sentence.push_back(c);
    }
    return result;
}


bool Agenda::fileExists(const string& ruta)
{
    fstream infile(ruta.c_str());
    return infile.good();
}

void Agenda::agregar(Persona& persona)
{
    if(file.is_open())
    {
        file<<persona.getNombre()<<","<<persona.getApellido()<<","<<persona.getCedula()<<","<<endl;
    }
}

void Agenda::agregarTodas(const vector<Persona>& personas)
{
    if(file.is_open())
    {
        for(Persona p: personas)
        {
            file<<p.getNombre()<<","<<p.getApellido()<<","<<p.getCedula()<<","<<endl;
        }
    }
}

vector<Persona> Agenda::leerTodo()
{
    vector<Persona> personas;
    if(file.good())
    {
        file.seekg(0,file.beg);//Nos ponemos al inicio del fichero
        string linea;
        while(getline(file,linea))
        {
            vector<string> tokens=split(linea,',');
            string nombre=tokens[0];
            string apellido=tokens[1];
            string cedula=tokens[2];

            Persona p(nombre,apellido,cedula);
            personas.push_back(p);

        }
    }
    return personas;
}

Agenda::~Agenda()
{
    file.close();
}

A start-up of the two classes working together would be this:

int main()
{
    //Creamos el objeto Agenda si el archivo no existe se crea, si existe se anade datos a la agenda
    Agenda agenda("C:\Users\usuario\Documents\agenda.txt");

    //Agregamos 1 persona
    Persona p=Persona("luis","arturo","0435845");
    agenda.agregar(p);

    vector<Persona> personas;
    personas.push_back(Persona("Mari","Perez","34353543"));
    personas.push_back(Persona("Jose","Arturo","9343533"));
    agenda.agregarTodas(personas);

    vector<Persona> datosLeidos=agenda.leerTodo();

    for(Persona p:datosLeidos)
    {
        cout<<p.getNombre()<<" "<<p.getApellido()<<" "<<p.getCedula()<<endl;
    }

    cout<<"\nPrograma terminado"<<endl;
    return 0;
}

In it we can see that the class Agenda is responsible for managing the creation and reading of our file, if the file does not exist it creates it and if it already exists it only adds records at the end, at the same time that it accesses the data.

    
answered by 26.12.2016 / 19:47
source
0

I recommend using JSON to do this, here a library Json

    
answered by 24.12.2016 в 17:26
0

To read a file you can use the inherited interface of C or the own objects of c ++.

In the case of choosing the C interface, everything is based on the FILE handler:

FILE* fich = fopen("fichero.txt","r");
if(!fich) return;

while(feof(fich))
{
  // Lectura de los registros
}
fclose(fich);

In the case of opting for c ++ objects you can use the iostream library:

std::ifstream fich("fichero.txt");
while(fich.good())
{
  // Lectura de los registros
}
fich.close();

If I do not specify a specific way to read the data it is because you have not indicated the way they are stored.

    
answered by 24.12.2016 в 23:14