第一种方法
#include<iostream>
#include<fstream>
#include <string>
using namespace std;
int main()
{
//将数据写入到csv文件夹中
ofstream ou("data.csv");
double a[10][5];
double t = 1;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 5; j++) {
a[i][j] = t;
t++;
ou << a[i][j] << ",";//将数据写入到csv中,通过","来实现进入下一个单元格,必不可少
}
ou << endl;
}
ou.close();
string temp;
ifstream iFile("data.csv");
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 5; j++) {
getline(iFile, temp, ',');
t = atof(temp.c_str());//将字符数据转换为浮点型数据
cout << t << " ";
}
cout << endl;
}
iFile.close();
return 0;
}
结果:
data.csv
第二种方法
#include<iostream>
#include<fstream>
#include <string>
using namespace std;
int main()
{
//将数据写入到csv文件夹中
ofstream ou("data.csv");
double a[10][5];
double t = 1;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 5; j++) {
a[i][j] = t;
t++;
ou << a[i][j] << ",";//将数据写入到csv中,通过","来实现进入下一个单元格,必不可少
}
ou << endl;
}
ou.close();
string temp;
ifstream iFile("data.csv");
int i=1;
while (getline(iFile, temp, ',')){
t = atof(temp.c_str());//将字符数据转换为浮点型数据
cout << t << " ";
if (i % 5 == 0) {//控制换行
cout << endl;
}
i++;
}
iFile.close();
return 0;
}
将多行多列的数据读取到数组中
string temp;
ifstream iFile("tra.csv");//训练数据
for (int i = 0; i < number; i++) {//number是行数
getline(iFile, temp);
string str;
istringstream isfp(temp);
int j = 0;
while (getline(isfp,str,','))
{
testdata[i][j] = atof(str.c_str());//将字符数据转换为浮点型数据
j++;//控制列数
}
}
iFile.close();