How to access elements of a vector of a type defined by struct?

1

In my code, I made the following struct declaration:

struct material {
    int idmaterial;
    double rho;
    double precokg;
};

I wanted to run this function, which reads the data from a file:

std::vector<material> le_material(std::string s)
{
    std::ifstream dados(s);
    dados.exceptions(std::ios::failbit |
            std::ios::badbit);

    int N{0};
    bool fim;
    std::vector<material> infomaterial;
    fim = dados.eof();

    while (fim == 0) {
        dados >> infomaterial[N].idmaterial;
        dados >> infomaterial[N].rho;
        dados >> infomaterial[N].precokg;
        N++;
        fim = dados.eof();
    }

    return infomaterial;
}

In this file, whose name is given as a function parameter, there is the information for each material. In each row there are 3 numbers, with the data to be read.

However, when running the code and executing this function on main, it fails to target.

From what I've been able to exploit, the error occurs at the moment when trying to pass the data from the file to an element of the "material" type vector. I came to find that it was a mistake in reading the file, but if I try to read something that I enter into the terminal, although it is possible to insert the value, the segmentation failure occurs, right after insertion.

I think the error should be in the way I'm trying to access an element of the vector, but searching on I could not find anything very enlightening.

    
asked by anonymous 14.05.2018 / 17:19

1 answer

1

The segmentation fault error occurs when trying to change data from the infomaterial vector without initializing it with elements (the vector is "empty").

The solution is to initialize the vector with a predetermined number of elements:

// Exemplo para 100 elementos
std::vector<material> infomaterial(100);

Or use, for example, the insert method or push_back before reading a file element:

material m = { 0, 0.0, 0.0 }; // Declara um elemento 'default'
fim = dados.eof();

while (!fim) {
  infomaterial.push_back(m); // Insere um novo elemento antes de ler os dados
  dados >> infomaterial[N].idmaterial;
  std::cout << infomaterial[N].idmaterial << std::endl;
...
    
14.05.2018 / 19:32