Why is there an error coming at the end of a file that ends with blank spaces in a while loop, using the >>read operator?

Asked

Viewed 49 times

1

I want to perform a reading function of a "material" vector (I created this type with "struct"). The reading will be executed from a file.

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

    std::vector<material> infomaterials;
    material mat_read;

    while (data >> mat_read.idmaterial) {
        data >> mat_read.idmaterial;
        data >> mat_read.rho;
        data >> mat_read.pricekg;
        infomaterials.push_back(mat_read);
    }

    return infomaterials;
}

The file I should read (and I cannot make changes) is the following, with spaces after all lines:

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 think reading every number on every line is going well. However, there is an error in the 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 (saved kernel image)

I tested by printing something on the screen before and after each read operation. It really does all 33 readings I expected. But after reading the 33rd value, it doesn’t even enter the while loop again and then shows the error.

Is it possible that as the date >> mat_read.idmaterial fails, give me the error message? This is happening because the file ends with spaces?

  • You’re reading the dice twice mat_read.idmaterial and, by setting the exceptions the variable dados does not exist. In its another question, I had already suggested another form of reading that should work

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.