2017-10-14 61 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; 
}