从文本文件读取 2D 数组错误

Reading from a text file into a 2d array error

本文关键字:数组 错误 2D 读取 文本 文件      更新时间:2023-10-16

我正在尝试将这些数据从文本文件读取到我的 2d 数组中。还有更多列,但下面的数据只是一小部分。我能够读取第一个数字"5.1",但打印出的大部分内容都是一些 0,然后是垃圾。我的代码做错了什么?

部分文本文件数据:

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;
}

您可以逐行读取数据,将逗号替换为空格。使用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;
}