簡體   English   中英

C ++編寫和讀取二進制文件中的雙精度矩陣

[英]C++ writing and reading matrices of doubles from a binary file

在上一個問題之后出現了一個新問題

我擴展了代碼以執行矩陣二進制文件I / O,並且在測試簡單的讀寫操作時,我僅檢索到矩陣的第一行...

我沒有找到錯誤,這是新代碼:

double** bytes_to_matrix_block(std::ifstream& iF, int size1, int size2) {
    double** m = new double*[size1];
    double read;
    int i = 0, j = 0;

    if(!iF) {
        std::cout << "opening file for reading error";
        throw 1;
    }
    while(i < size1 && !iF.eof()) {
        m[i] = new double[size2];
        while(j < size2 && !iF.eof()) {
            iF.read( reinterpret_cast<char*>( &read ), sizeof read );
            m[i][j] = read;
            std::cout << read << ", ";
            j++;
        }
        std::cout << std::endl;
        i++;
    }
    if(i < size1 || j < size2) {
        std::cout << "premature end of file while reading..." << std::endl;
        throw 1;
    }
    return m;
}

void matrix_block_to_bytes(double** m, int size1, int size2, std::ofstream& oF){

    if(!oF){
        std::cout << "opening file for writing error";
        throw 1;
    }

    double cdbl;

    for(int i = 0; i < size1; i++){
        for(int j = 0; j < size2; j++){
            cdbl = m[i][j];
            std::cout << cdbl << ", ";
            oF.write( reinterpret_cast<char*>( &cdbl ), sizeof cdbl );
        }
        std::cout << std::endl;
    }
}

預先感謝

讀取時,您忘記將j重新設置為0以換行

while(i < size1 && !iF.eof()) {
// Missing:
j = 0;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM