1
In my code, I made the following statement of struct:
struct material {
int idmaterial;
double rho;
double precokg;
};
I wanted to run this function, which reads 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 of each material. In each line there are 3 numbers, with the data to be read.
However, when running the code and executing this function in main, it gives segmentation failure.
From what I was able to explore, the error occurs at the moment when trying to pass the data from the file to a vector element of type "material". I came to think that it was an error in reading the file, but if I try to read something that I insert in the terminal, although it is possible to insert the value, also occurs the segmentation failure, soon after the insertion.
I believe that the error should be in the way I am trying to access an element of the vector, but searching on could not find anything very enlightening.
You probably need to allocate the space in the vector before using it, like:
std::vector<material> infomaterial(10);
(for 10 elements), or insert each element with Insert– Gomiero
Ah, that’s right, thank you! I thought it was more complicated than that, but now I can read it like this: 1) I declare a material type variable, mat_lido. 2) No while, I read like this: data >> mat_lido.idmaterial; data >> mat_lido.Rho; data >> mat_lido.precokg; infomateriais.push_back(mat_lido); Now I’m having problems with the moment the program should finish reading, but I’m creating another topic about it.
– Gabriel Henrique