简体   繁体   English

从 C++ 中的文本文件读取时忽略字符

[英]Ignoring Characters while reading from a text file in C++

I am new to c++.我是 c++ 的新手。 I want to read data from a STL file which looks like我想从 STL 文件中读取数据,看起来像

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.同样的事情将 go 以不同的值进行 100 次。

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:您可以将矩阵包装在 class 中并为其创建自定义提取运算符:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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