简体   繁体   中英

Ignoring Characters while reading from a text file in C++

I am new to c++. I want to read data from a STL file which looks like

facet normal -0 -0 -1

outer loop

vertex 2.49979 1.14163 0.905974

vertex 2.49979 1.01687 0.905974

vertex 2.22582 1.68468 0.905974

endloop

endfacet 0

and the same thing will go on with different values for say 100 times.

Now I want to read and store only the numerical value in form of a 2D array. It would be even better if i can totally neglect all the other things except the vertex values as I have to make use of only those values. please help me out with this.

You could wrap the matrix in a class and create a custom extraction operator for it:

struct MyMatrix {
    double values[3][3];
};

std::istream & operator >>(std::istream & stream, MyMatrix & value) {
    std::string dummy;

    std::getline(stream, dummy);
    std::getline(stream, dummy);
    std::getline(stream, dummy);
    std::getline(stream, dummy); // discard first four lines
    for(int i = 0; i < 3; i++)
       stream >> dummy >> value.values[i][0] >> value.values[i][1] 
              >> value.values[i][2];

    std::getline(stream, dummy);
    std::getline(stream, dummy);
    std::getline(stream, dummy);
    std::getline(stream, dummy); // discard last four lines

    return stream;
}

With this operator, you can read the entire file like this:

std::ifstream file("data.txt");
std::vector<MyMatrix> data(std::istream_iterator<MyMatrix>(file),
                           (std::istream_iterator<MyMatrix>()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM