2017-10-14 85 views
0

我想從文本文件中讀取這些數據到我的2d數組中。還有更多的列,但下面的數據只是一小部分。我能夠讀取第一個數字「5.1」,但大部分正在打印出來的數字都是0的垃圾。我在做什麼錯我的代碼?從文本文件讀取到2d數組錯誤

部分文本文件的數據:

5.1,3.5,1.4,0.2

4.7,3.2,1.3,0.2

4.6,3.1,1.5,0.2

5.0, 3.6,1.4,0.2

5.4,3.9,1.7,0.4

if (!fin) 
{ 
    cout << "File not found! " << endl; 
} 

const int SIZE = 147; 

string data[SIZE]; 

double data_set[SIZE][4]; 


for (int i = 0; i < SIZE; i++) 
{ 
    for (int j = 0; j < 4; j++) 
     fin >> data_set[i][j]; 
} 

for (int i = 0; i < SIZE; i++) 
{ 
    for (int j = 0; j < 4; j++) 
     cout << data_set[i][j] << " "; 
     cout << endl; 
} 
+0

文件中的值用逗號分隔。你必須閱讀每一行並用逗號分隔。 –

+0

這是很多的重複。在「C++讀取文件2d數組」中搜索StackOverflow。始終先搜索,比發佈正確的速度快得多,*等待一個或多個回覆。 –

+1

只有在編譯時已知數據大小的情況下,才應該使用'for'循環來讀取文件。如果數據量是在運行時確定的,則使用'while'和'std :: vector'。 –

回答

0

您可以逐行讀取數據,用空格替換逗號。將行轉換爲流,使用std::stringstream並讀取雙精度值。

>>運算符在到達流末尾時會失敗。你必須在那個時候打破循環。您應該使用<vector<vector<double>> data而不是固定大小的二維數組。

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

... 
string line; 
int row = 0; 
while(fin >> line) 
{ 
    for(auto &c : line) if(c == ',') c = ' '; 
    stringstream ss(line); 

    int col = 0; 
    while(ss >> data_set[row][col]) 
    { 
     col++; 
     if (col == 4) break; 
    } 
    row++; 
    if (row == SIZE) break;//or use std::vector 
} 

for (int i = 0; i < row; i++) 
{ 
    for (int j = 0; j < 4; j++) 
     cout << data_set[i][j] << " "; 
    cout << endl; 
}