Read file (.txt) C ++

0

My problem is this:

void read () {
        string name, ciudad;
        int cont = 0;
        ifstream read;
        reader.open ("usuarios.txt", ios::out | ios::in);
        if (lectura.is_open())
        {    
            while (!reader.eof())
            {
                reader >> name;
                reader >> ciudad;
                usuarios[cont].name = name;
                usuarios[cont].ciudad = ciudad;
                cont ++;
            }
        }
        else
        {
            cout << "¡Error! El archivo no pudo ser abierto." << endl;
        }
        lectura.close();
    }

For example, if the text file is:

  

Carlos Juan Griego

     

John San Antonio

the variables would look like this:

  

user1 = carlos juan

     

user2 = john san

Because every time he finds a space he interprets it as passing to the next variable or reads the next variable.

The ideal thing for this is to use a flag and the text file would look like this:

  

Carlos # Juan Griego

     

John # San Antonio

So every time you get a "#" it assigns the indicated variable to one to avoid the problem of spaces.

An example of this in JAVA:

public void reader(people personas[]) {
    try {
        File f = new File("agenda.txt");
        if (f.exists()) {
            FileReader fr = new FileReader(f);
            BufferedReader br = new BufferedReader(fr);
            String linea;
            int i = 0;
            while (((linea = br.readLine()) != null) && (i < 10)) {
                String[] contacto = linea.split("%"); //Se crea un array de string y se signa a cada posición al encontrar la bandera.
                personas[i] = new people(contacto[0], contacto[1], contacto[2], Integer.parseInt(contacto[3]));
                i++;
            }
        } else {
        }
    } catch (Exception e) {
        System.out.println(e);
        System.out.println("Agenda no existente.");
    }
}

In the previous example, the used flag is "%".

Another example of my question:

Suppose the text file is as follows:

  

carlos guevara 28 san antonio

     

jesus snow 88 cuerna vaca

The variables are read like this:

  

name: Carlos

     

age: guevara

     

city: 28

(in this example carlos guevara is the name, 28 the age, san antonio the city) This is how the text file is written. The problem is that when the program reads the string every space is a variable that is the problem.

One solution would be:

  

carlos guevara # 28 # san antonio

     

jesus snow # 88 # cuerna vaca

The way to save in each variable is:

  

name: carlos guevara

     

age: 28

     

city: san antonio

(note that this is the flag to separate each variable)

This separates each variable at the moment of reading, (these are the so-called flags).

As you can see my problem is that there is no way to do it in C ++ (I am learning the language), to do so with the flags that divide the string when finding the flag and assign it to each variable. I hope you understand me Question. I need your help in this doubt I have, please. : D

    
asked by Cookie Rabbit 19.04.2017 в 20:40
source

2 answers

1

I see that you try to itemize a string with respect to space or a separator {#,%, etc}. My example works under spaces.

I recommend you use: strtok

link

The code in a very basic way would look like this:

void read () {
    char ln[500], ciudad;
    int cont = 0;
    ifstream read;
    char *info[] = {"Nombre: ", "Apellido: ", "Edad: "};
    int pt = 0; 
    char * pch;

    read.open ("usuarios.txt", ios::out | ios::in);

    if (read.is_open())
    {    
        while (!read.eof())
        {
            // Obtiene linea del archivo
            read.getline(ln, 500);

            // Itemize la cadena para obtener cada uno de los elementos necesarios
            pch = strtok (ln," ");
            pt = 0;
            while (pch != NULL)
            {
                // Muestro el contenido de info para ver que los campos se obtiene de modo adecuado
                // pero tu deberias hacer el casteo correspondiente y asignar a variables.
                cout<< info[pt] << pch << endl;
                pch = strtok (NULL, " ");

                pt ++;
                if(pt > 2)
                {
                    // En caso de que la cadena contengas mas campos de los que puedo procesar
                    break;
                }
            }

            cont ++;
        }
    }
    else
    {
        cout << "¡Error! El archivo no pudo ser abierto." << endl;
    }

    read.close();
}

I hope it helps you.

Greetings.

    
answered by 20.04.2017 в 03:14
0

I do not know how you could do what java samples in C ++, but as a solution to your problem, as I commented, is to create an object called the way you want. This object will contain the first and last name, and then return it to the variable name as you wish.

As a result, your code would be such that:

void read () {
    string name, ciudad;
    int cont = 0;
    ifstream read;
    reader.open ("usuarios.txt", ios::out | ios::in);
    if (lectura.is_open())
    {    
        while (!reader.eof())
        {
            reader >> objeto.nombre;
            reader >> objeto.apellido;
            reader >> ciudad;
            name= objeto.nombre+" "+objeto.apellido;
            usuarios[cont].name = name;
            usuarios[cont].ciudad = ciudad;
            cont ++;
        }
    }
    else
    {
        cout << "¡Error! El archivo no pudo ser abierto." << endl;
    }
    lectura.close();
}

The only requirement is that the 3 variables are string.

    
answered by 20.04.2017 в 01:17