如何从文件中读取“不均匀”矩阵并将其存储到2D数组中?

约翰·阿尔珀托

我正在做一个实验,该实验需要我切换到仍在学习的C ++。我需要将数据从文件读取到2D数组中,其中文件中的数据由以矩阵格式布置的浮点数组成。但是,数据文件中矩阵的每一行都有不同的列数,例如:

1.24 3.55 6.00 123.5
65.8 45.2 1.0
1.1 389.66 101.2 34.5 899.12 23.7 12.1

好消息是,我知道文件可能具有的最大行数/列数,至少现在,我并不特别担心内存优化。我想要的是一个2D数组,其中相应的行/列与文件的行/列匹配,而所有其他元素都是某个已知的“虚拟”值。

我的想法是遍历文件的每个元素(逐行),识别一行的结尾,然后开始读取下一行。不幸的是,我在执行此操作时遇到了麻烦。例如:

#include <iostream>
#include <fstream>

int main() {

const int max_rows = 100;
const int max_cols = 12;
//initialize the 2D array with a known dummy
float data[max_rows][max_cols] = {{-361}};

//prepare the file for reading
ifstream my_input_file;
my_input_file.open("file_name.dat");

int k1 = 0, k2 = 0; //the counters
while (!in.eof()) { //keep looping through until we reach the end of the file
    float data_point = in.get(); //get the current element from the file
    //somehow, recognize that we haven't reached the end of the line...?
        data[k1][k2] = next;
    //recognize that we have reached the end of the line
        //in this case, reset the counters
        k1 = 0;
        k2=k2+1;
}
}

所以我一直无法弄清楚索引。问题的一部分是,尽管我知道字符“ \ n”标记了一行的结尾,但与文件中的浮点数相比,它的类型不同,所以我很困惑。我在想这个错误的方式吗?

因为R

如果您坚持下去,则无需提前知道限制std::vector这里是一些将读取文件的示例代码(假设文件中没有非浮点数)。

using Row = std::vector<float>;
using Array2D = std::vector<Row>;

int main() {
    Array2D data;
    std::ifstream in("file_name.dat");
    std::string line;
    Row::size_type max_cols = 0U;
    while (std::getline(in, line)) { // will stop at EOF
        Row newRow;
        std::istringstream iss(line);
        Row::value_type nr;
        while (iss >> nr) // will stop at end-of-line
            newRow.push_back(nr);
        max_cols = std::max(max_cols, newRow.size());
        data.push_back(std::move(newRow)); // using move to avoid copy
    }
    // make all columns same length, shorter filled with dummy value -361.0f
    for(auto & row : data)
        row.resize(max_cols, -361.0f);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

C ++中的2D整数数组,每行中元素数量不均匀

如何从文件中读取所有字符并将其存储在不带\ n的2d数组中?

如何接受用户的值并将其存储到Java中的2D数组中?

在R中建立不均匀矩阵的数组

读取文件并将值存储到2D数组中

如何从文件中读取数据并将其存储到矩阵中

列长度不均匀的文件中读取的熊猫

在矩阵中检测不均匀方向

从txt文件读取整数并将其存储到数组中

如何读取文件并将其数据存储到列表中?

如何迭代获取特定的struct元素并将其存储到C中的2D数组中?

读取Java中的文件并将其内容放入2D数组中

如何将从文件读取的数据存储到2D数组中

如何读取文件并将其内容存储在 C 中的矩阵中?

从ppm文件中读取RGB值,然后使用结构将其存储到称为“图像”的2d数组中(动态数组)

从文件中读取数据并将其存储到结构中

拆分2D numpy数组,可能出现不均匀拆分

如何在Matlab中将2D矩阵序列存储到3D数组中?

从bash读取yml文件并将其存储到变量中

Groovy 逐行读取文件并将其存储到列表中

从文件读取并将其存储到文本框中

从Ruby中的输入文件中删除不均匀的空间

从文本文件读取整数并将其存储到数组中

以不均匀的概率从 0 到 1 中采样

For循环到CSV导致Python中的行不均匀

如何从Julia中不均匀排列的数组中插值数据?

如何每次逐行读取CSV文件并将其存储到新行的新CSV文件中?

如何在Javascript中逐行读取文件并将其存储在数组中

如何读取文件的内容并将其存储在c#中的格式化数组中