gpt4 book ai didi

c++ - 如何从文件中读取 "uneven"矩阵,并存储到二维数组中?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:49:52 24 4
gpt4 key购买 nike

我正在进行一项实验,需要我切换到 C++,我仍在学习它。我需要将文件中的数据读入二维数组,其中文件中的数据由 float 组成,以矩阵格式排列。但是,数据文件中矩阵的每一行都有不同的列数,例如:

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

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

我的想法是遍历文件的每个元素(逐行),识别一行的结尾,然后开始阅读下一行。不幸的是,我无法执行此操作。例如:

#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”表示一行的结尾,但与文件中的 float 相比,它属于不同的类型,所以我不知所措。我是不是想错了?

最佳答案

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

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

关于c++ - 如何从文件中读取 "uneven"矩阵,并存储到二维数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54734548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com