简体   繁体   English

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

[英]How to read an “uneven” matrix from a file, and store into a 2D array?

I'm working on an experiment that requires me to switch over to C++, which I'm still learning. 我正在进行一项实验,要求我切换到C ++,我还在学习。 I need to read data from a file into a 2D array, where the data in the file is composed of floating point numbers, laid out in a matrix format. 我需要将文件中的数据读入2D数组,其中文件中的数据由浮点数组成,以矩阵格式排列。 However, each row of the matrix in the data file has a different number of columns, for example: 但是,数据文件中矩阵的每一行都有不同的列数,例如:

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

The good news is that I know the maximum number of possible rows/columns the file might have, and at least right now, I'm not particularly worried about optimization for memory. 好消息是我知道文件可能有的最大行/列数,至少现在,我并不特别担心内存优化。 What I would like is to have a 2D array where the corresponding rows/columns match those of the file, and all the other elements are some known "dummy" value. 我想要的是有一个2D数组,其中相应的行/列与文件的行匹配,所有其他元素都是一些已知的“虚拟”值。

The idea I had was to loop through each element of the file (row by row), recognize the end of a line, and then begin reading the next line. 我的想法是循环遍历文件的每个元素(逐行),识别一行的结尾,然后开始阅读下一行。 Unfortunately I'm having trouble executing this. 不幸的是我在执行此操作时遇到了麻烦。 For example: 例如:

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

And so I haven't been able to figure out the indexing. 所以我无法弄清楚索引。 Part of the problem is that although I'm aware that the character "\\n" marks the end of a line, it is of a different type compared to the floating point numbers in the file, and so I'm at a loss. 问题的一部分是虽然我知道字符“\\ n”标记了一行的结尾,但与文件中的浮点数相比,它的类型不同,所以我很茫然。 Am I thinking about this the wrong way? 我是否以错误的方式思考这个问题?

You don't need to know the limits in advance if you stick to std::vector . 如果你坚持使用std::vector你不需要事先知道限制。 Heres some example code that will read the file (assuming no non-floats in the file). 下面是一些将读取文件的示例代码(假设文件中没有非浮点数)。

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

Here is starting point, I will be working on code that you can use. 这是起点,我将研究您可以使用的代码。 Use two dimensional vector vector<vector<double>> and you can use getline() to get the line as a string than use string stream to get decimals from string. 使用二维矢量vector<vector<double>> ,您可以使用getline()将行作为string不是使用string stream从字符串中获取小数。

And here is the code 这是代码

#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>

int main (void) {
    std::vector<std::vector<double>> matrix;

    std::ifstream inputFile;
    inputFile.open("test.txt");
    char line[99];
    for (int i = 0; inputFile.getline(line, sizeof(line)); ++i) {    
        std::stringstream strStream (line);
        double val = 0.0;
        matrix.push_back(std::vector<double>());
        while (strStream >> val)
            matrix[i].push_back(val);
    }

    return 0;
}

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

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