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