【问题标题】:c++ reading several arrays from several filec ++从几个文件中读取几个数组
【发布时间】:2016-09-12 09:29:03
【问题描述】:

我有几个文本文件,file_1.dat file_2.dat .....它们每个都包含这样的三列

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

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

【问题讨论】:

    标签: c++ arrays file


    【解决方案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);
    }
    

    【讨论】:

    • 谢谢!如何忽略第一行是 x |是 | z?
    • 您可以简单地使用正则表达式。您将每一行传递给 regex_search,如果它与正则表达式匹配,您将附加值,但是,如果它不匹配,您可以简单地忽略该行。
    【解决方案2】:

    编写一个函数,将一个文件的内容附加到您的数组中。 在遍历所有文件的循环中调用此函数。

    【讨论】:

    • 请更具体!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    相关资源
    最近更新 更多