How to detect the end of reading a file in a loop with while in C ++

0

In my code, you have the struct:

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

And the reading function of a data vector of type "material", from a file:

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

    std::vector<material> infomateriais;
    material mat_lido;
    bool fim;
    fim = dados.eof();

    while (fim == false) {
        dados >> mat_lido.idmaterial;
        dados >> mat_lido.rho;
        dados >> mat_lido.precokg;
        infomateriais.push_back(mat_lido);
        fim = dados.eof();
    }

    return infomateriais;
}

Since the file to be read contains the following data:

1   1.02    82.76   
2   2.81    29.45   
3   1.46    14.41   
4   1.15    31.54   
5   1.04    71.10   
6   1.11    87.05   
7   2.84    13.81   
8   1.56    27.55   
9   2.63    71.30   
10  0.87    25.59   
11  2.99    24.83   

I believe that reading the data is ok. However, the program gives an error in execution when it reaches the end of the file:

  

terminate called after throwing an instance of   'std :: ios_base :: failure [abi: cxx11]' what (): basic_ios :: clear:   iostream error Aborted (recorded core image)

At first, I discovered that it is because the eof () function actually only returns true when a read attempt is made that reaches the end of the file, so , the program would still try to read.

Some questions:

  • Is there any way to use eof () without trying to make a reading and making a mistake in running the program?
  • I tried to use the while condition with the > > , checking was successful in reading and continued to make mistakes because, I researched, he would try to read the final white space and would not detect which is the end of the file. So, would it be better to use get () ? As could this be done?
asked by anonymous 14.05.2018 / 19:36

0 answers