c ++从几个文件中读取几个数组

时间:2016-09-12 09:29:04

标签: c++ arrays file

我有几个文本文件,file_1.dat file_2.dat .....。它们每个都包含三列,如下

x | y | z
1   2   3
5   8   9
4   3   1
.....

我想定义三个数组X [],Y [],Z [],其中X []记录所有文件的第一列中的数字,Y []记录所有文件的第二列中的数字和Z []保存所有文件的第三列。所以代码应该有一个循环超过文件的数量。此外,代码应忽略第一行(即数据文件的标题)。最简单的方法是什么?

2 个答案:

答案 0 :(得分:1)

基本上你只是迭代你的所有文件并将文件中的所有坐标附加到一个矢量缓冲区..

这是非常简单的()代码:

struct vec3 {
    int x;
    int y;
    int z;
    vec3(int a, int b, int c) {
        x = a;
        y = b;
        z = c;
    }
}

vec3 parseVec3Line(const char* str) {
    // do your real implementation for parsing each line here
    return vec3(str[0], str[2], str[4]);
}

int main() {
    std::vector<vec3> data;

    // iterate over all files you want to read from
    for(const auto& it : files) {
        int fd = open(it); // open the file
        while(!EOF) { // read all lines
            read_line(buffer, fd); // copy each line from file to temp buffer
            data.push_back(parseVec3Line(buffer)); // append the parsed data
        }
    }
    return 0;
}

<小时/> 我建议你看一下regular expressions解析文件 如果您知道某些数字之间会有空格用作分隔符,您只需执行以下操作:

bool parseVec3Line(const char* str, vec3& vec) {
    // this regular expression will separate the input str into 4 groups..
    // str(0) contains the input str
    // str(1) contains x coord
    // str(2) contains y coord
    // str(3) contains z coord
    static std::regex regx("^([0-9]+)[ ]+([0-9]+)[ ]+([0-9]+)$");
    std::smatch match;

    if(std::regex_search(str, match, regx) && match.size() != 4)
        return false;

    vec.x = str2int(match.str(1));
    vec.y = str2int(match.str(2));
    vec.z = str2int(match.str(3));
    return true;
}

在循环中,您可以执行以下操作:

while(!EOF) {
    read_line(buffer, fd);
    vec3 vec;
    if(!parseVec3Line(buffer, vec))
        continue;
    data.push_back(vec);
}

答案 1 :(得分:0)

编写一个函数,将一个文件的内容追加到数组中。 在循环中调用此函数,迭代所有文件。

相关问题