2016-12-30 38 views
0

我有一個簡單的程序,試圖將二維數據讀入堆分配的浮點數組中。該計劃如下。讀取二維表到數組

#include <iostream> 
#include <fstream> 


void read_file(std::ifstream &inFile, float **arr, unsigned m, unsigned n) 
{ 

    for(unsigned i = 0; i < m; ++i) { 
     for(unsigned j = 0; j < n; ++j) { 
      inFile >> arr[i][j]; 
      std::cout << arr[i][j]; 
     } 
     std::cout << std::endl; 
    } 

} 


int main() { 

    const unsigned m = 20; 
    const unsigned n = 1660; 

    float **A = new float *[m]; // alloc pointers to rows 1,...,m 
    for(unsigned row = 0; row < m; row++) A[row] = new float [n]; // alloc columns for each row pointer 

    std::ifstream inFile("data.dat"); 
    read_file(inFile, A, m, n); 



    // DEALLOC MEMORY 
    for(unsigned row = 0; row < m; row++) delete [] A[row]; // dealloc columns for each row pointer 
    delete [] A; // dealloc row pointers 


    return EXIT_SUCCESS; 
} 

的數據是0-1條目表(見這裏:data),其是很好的行取向,並且具有20行和1660列。我將打印添加到read_file函數中以查看錯誤,並且僅打印零,但至少打印正確的數量(20 * 1660個零)。

數據似乎是製表符分隔的;是問題還是我的方法完全無效?

+0

有趣的選擇如何'VECTOR',你不使用它! –

+0

我從'vector'開始,但後來我試着去了解'new'關鍵字。 – ELEC

+0

這是一個不錯的[C++書籍]列表(http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。我建議你看看它。對於* 2D陣列*使用矢量向量。 – 2016-12-30 10:05:17

回答

1

這正是如果文件不存在可能發生的事情。

您應該檢查創建​​對象後,該文件存在,比如像這樣:

std::ifstream inFile("data.dat"); 
if (!inFile) 
{ 
    std::cerr << "cannot open input" << std::endl; 
    return 1; 
} 

如果文件不存在,cin不把數據數組中,並有機會(我有0 +其他奇怪的東西),所以總結它未定義的行爲

請注意,如果該文件存在,您的程序將按預期工作。它甚至會更好,檢查文件後看了一個值,以確保該文件還有許多價值預期:

for(unsigned j = 0; j < n; ++j) { 
    inFile >> arr[i][j]; 
    if (!inFile) 
    { 
     std::cerr << "file truncated " << i << " " << j << std::endl; 
     return; 
    } 
    std::cout << arr[i][j]; 
} 
+0

謝謝Jean。你是正確的,我需要指定工作目錄到我的IDE,現在它工作! – ELEC