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.