从文本文件读取 2D 数组错误
Reading from a text file into a 2d array error
我正在尝试将这些数据从文本文件读取到我的 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;
}
相关文章:
- 类动态数组错误
- 如何返回多维数组?错误C2440
- 数组错误(不允许类型不完整)
- C++ 将文件读取到数组错误:'operator>>'不匹配
- 不断增加的指针数组 错误:赋值中的类型不兼容
- 从文本文件读取 2D 数组错误
- 动态结构数组错误
- 旋转数组 - 错误
- 按字母顺序排序名称,数组错误
- 因为每个循环都读取数组错误
- 二维数组错误
- C 获取数组错误
- 编译时出现字符串数组错误
- c++2维指针类数组错误(使用openframework)
- C++数组错误
- C++上数组错误的大小
- C++数组错误:访问冲突读取位置0xC0000005
- c++2D数组错误
- C++:为“char [4]”数组错误获取太多初始值设定项
- 分段错误(核心转储)排序字符串数组错误