簡體   English   中英

如何從文件中讀取“不均勻”矩陣,並存儲到2D數組中?

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

我正在進行一項實驗,要求我切換到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”標記了一行的結尾,但與文件中的浮點數相比,它的類型不同,所以我很茫然。 我是否以錯誤的方式思考這個問題?

如果你堅持使用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);
}

這是起點,我將研究您可以使用的代碼。 使用二維矢量vector<vector<double>> ,您可以使用getline()將行作為string不是使用string stream從字符串中獲取小數。

這是代碼

#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