开发者

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

开发者 https://www.devze.com 2023-03-10 18:51 出处:网络
I am开发者_运维问答 new to c++. I want to read data from a STL file which looks like facet normal -0 -0 -1

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>()));
0

精彩评论

暂无评论...
验证码 换一张
取 消