Basically you have a text file ... and reading a file of that type is one of the easiest operations to do in C ++.
With these simple instructions you read a line from a text file:
if (std::ifstream datos{"tu_archivo.dat"})
{
std::string linea;
std::getline(datos, linea);
}
As your data goes from 3 to 3 lines and each line follows a closed format, we can read a complete data in your structure Datos
in the following way:
if (std::ifstream datos{"tu_archivo.dat"})
{
std::string linea;
Datos d;
std::getline(datos, linea);
d.Id = std::stoi(linea.substr(4));
std::getline(datos, linea);
d.Nombre = linea.substr(8);
std::getline(datos, linea);
d.Apellido = linea.substr(10);
}
If you want to store it in a data collection, just need to create it and read the file sequentially, I advise you to separate the reading process in a function:
Datos leer_un_dato_de_archivo(std::ifstream &archivo)
{
std::string linea;
Datos d;
std::getline(archivo, linea);
d.Id = std::stoi(linea.substr(4));
std::getline(archivo, linea);
d.Nombre = linea.substr(8);
std::getline(archivo, linea);
d.Apellido = linea.substr(10);
return d;
}
This way you can make the call to the function in a loop and fill in:
int main()
{
std::vector<Datos> d;
if (std::ifstream datos{"tu_archivo.dat"})
{
while (datos)
{
d.push_back(leer_un_dato_de_archivo(datos));
}
}
return 0;
}
Think that this example code does not have in the gutter that the input data does not follow the format or that there are incomplete entries.